dmonder February 2016

Change names of only some columns

I have a set of data that looks like the following:

V1,V2,V3,V4,lm,Q1.1,Q1.2
"ID","Set","Name","Status","lm","First Question","Second Question"
"RX0102","Default","RespondentName1",0,,1,1
"RT1832","Default","RespondentName2",0,,1,1

I want to take all of the columns with names that start with V and rename them using the value from the first row. I know how to get the names (colnames(f[,c(grep("^V[0-9]*$",names(f)))]) which will return "V1", "V2", "V3", "V4") and even the positions (grep("^V[0-9]*$",names(f)) which will return 1, 2, 3, 4) of the columns, and I know how to get the respective values from the first row (f[1,c(grep("^V[0-9]*$", names(f)))]). I just can't seem to assign the first row values to the names. I have tried this:

colnames(f[,c(grep("^V[0-9]*$",names(f)))]) <- f[1,c(grep("^V[0-9]*$", names(f)))]

but that does nothing. Can someone please tell me what I am doing wrong?

Answers


HubertL February 2016

You could do it that way:

colnames(f)[grep("^V[0-9]*$",names(f))] <- f[1,c(grep("^V[0-9]*$", names(f)))]


user5249203 February 2016

If you know the order of the columns V ...this should work too.

V1 <- c('Column Hey','1e','2e','3e','4e','5e')
V2 <- c('Column Why', 'a', 'b','c', 'd', 'e') 
X <- data.frame(V1,V2,stringsAsFactors =F)
colnames(X)[1:2] <-  as.character(X[1,1:2])
X<-X[2:nrow(X),]

Post Status

Asked in February 2016
Viewed 2,012 times
Voted 8
Answered 2 times

Search




Leave an answer