Rename column name of data frame in R language

Posted by telvitajoel on Tue, 26 Nov 2019 23:26:33 +0100

Error type
Error: All arguments must be named

Rename in plyr is different from rename in dplyr

plyr::rename

rename(data, c(old=new))

dplyr::rename

rename(data, new = old)

Example

For example, the default is the rename of plyr. If you run the following command, an error will be reported:

d <- data.frame(old1=1:3, old2=4:6, old3=7:9)
d
library(tidyverse)
rename(d, c("old2"="two", "old3"="three"))
rename(d, c(old2="two", old3="three"))

Result

> d <- data.frame(old1=1:3, old2=4:6, old3=7:9)
> d
  old1 old2 old3
1    1    4    7
2    2    5    8
3    3    6    9
> library(tidyverse)
> rename(d, c("old2"="two", "old3"="three"))
Error: All arguments must be named
> rename(d, c(old2="two", old3="three"))
Error: All arguments must be named

Correct opening mode:

d <- data.frame(old1=1:3, old2=4:6, old3=7:9)
d
rename(d, two=old2, three=old3)

Result:

> d <- data.frame(old1=1:3, old2=4:6, old3=7:9)
> d
  old1 old2 old3
1    1    4    7
2    2    5    8
3    3    6    9
> rename(d, two=old2, three=old3)
  old1 two three
1    1   4     7
2    2   5     8
3    3   6     9

Or use plyr to modify in the first way:

d <- data.frame(old1=1:3, old2=4:6, old3=7:9)
d
library(tidyverse)
plyr::rename(d, c("old2"="two", "old3"="three"))
plyr::rename(d, c(old2="two", old3="three"))

Result:

> d <- data.frame(old1=1:3, old2=4:6, old3=7:9)
> d
  old1 old2 old3
1    1    4    7
2    2    5    8
3    3    6    9
> library(tidyverse)
> plyr::rename(d, c("old2"="two", "old3"="three"))
  old1 two three
1    1   4     7
2    2   5     8
3    3   6     9
> plyr::rename(d, c(old2="two", old3="three"))
  old1 two three
1    1   4     7
2    2   5     8
3    3   6     9

Get it done!!!

Key point, dplyr is to put the new name in front, the old name in the back, and no quotes, no c(), more convenient!!!

In addition, select in dplyr can also choose + this name to directly specify the number of columns!!!

d <- data.frame(old1=1:3, old2=4:6, old3=7:9)
d
select(d,one=1,three=3)

Result:

> d <- data.frame(old1=1:3, old2=4:6, old3=7:9)
> d
  old1 old2 old3
1    1    4    7
2    2    5    8
3    3    6    9
> select(d,one=1,three=3)
  one three
1   1     7
2   2     8
3   3     9