简体   繁体   中英

Using R: Renaming columns in the dataframe

I have just started learning R, but i am having trouble understaning it.

So this is the requested action "Use the names() command to rename the columns of Mymatr in the data frame."

Mydat <- data.frame(Multof2,Language,mylet,Mymatr,Lessthan15=Multof2<15) Mydat

names(Mydat) names

names(Mydat)[4:7] <- c("Mymatr1","Mymatr2","Mymatr3","Mymatr4") Mydat

and this is what i am receiveing Mydat Multof2 Language mylet X1 X2 Lessthan15 1 2 English A 1 21 TRUE 2 4 English Z 2 22 TRUE 3 6 English C 3 23 TRUE 4 8 English C 4 24 TRUE 5 10 English Q 5 25 TRUE 6 12 Greek V 1 26 TRUE 7 14 Greek C 2 27 TRUE 8 16 Greek V 3 28 FALSE 9 18 Greek W 4 29 FALSE 10 20 Greek A 5 30 FALSE 11 22 English P 1 31 FALSE 12 24 English A 2 32 FALSE 13 26 English E 3 33 FALSE 14 28 English R 4 34 FALSE 15 30 English V 5 35 FALSE 16 32 Greek J 1 36 FALSE 17 34 Greek Q 2 37 FALSE 18 36 Greek I 3 38 FALSE 19 38 Greek W 4 39 FALSE 20 40 Greek V 5 40 FALSE

names(Mydat) [1] "Multof2" "Language" "mylet" "X1" "X2" "Lessthan15" names function (x).Primitive("names")

names(Mydat)[4:7] <- c("Mymatr1","Mymatr2","Mymatr3","Mymatr4","Mymatr5","Mymatr6","Mymatr7") Error in names(Mydat)[4:7] <- c("Mymatr1", "Mymatr2", "Mymatr3", "Mymatr4", : 'names' attribute [7] must be the same length as the vector [6] In addition: Warning message: In names(Mydat)[4:7] <- c("Mymatr1", "Mymatr2", "Mymatr3", "Mymatr4", : number of items to replace is not a multiple of replacement length names(Mydat)[4:7] <- c("Mymatr1","Mymatr2","Mymatr3","Mymatr4",) Error in c("Mymatr1", "Mymatr2", "Mymatr3", "Mymatr4", ): argument 5 is empty names(Mydat)[4:7] <- c("Mymatr1","Mymatr2","Mymatr3","Mymatr4") Error in names(Mydat)[4:7] <- c("Mymatr1", "Mymatr2", "Mymatr3", "Mymatr4"): 'names' attribute [7] must be the same length as the vector [6]

names(Mydat)[4:7] <- c("Mymatr1","Mymatr2","Mymatr3") Error in names(Mydat)[4:7] <- c("Mymatr1", "Mymatr2", "Mymatr3"): 'names' attribute [7] must be the same length as the vector [6] In addition: Warning message: In names(Mydat)[4:7] <- c("Mymatr1", "Mymatr2", "Mymatr3"): number of items to replace is not a multiple of replacement length

I have tried adding and removing names, as it says that the length is not the same as the vector.

Any ideas on what i am doing wrong?

Thnx

This will work:

names(Mydat)[4:7] <- c("Mymatr1","Mymatr2","Mymatr3","Mymatr4")

or

library(data.table)

setnames(Mydat, old = c(4:7), new = c("Mymatr1","Mymatr2","Mymatr3","Mymatr4"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM