Reputation: 904
I know there's a simple solution, but I keep getting error messages. Given this sample data frame:
y <- c(1,2,3)
a <- c(2,4,6)
b <- c(4,8,12)
c <- c(8,16,24)
z <- as.data.frame(cbind(y,a,b,c))
z
y a b c
1 1 2 4 8
2 2 4 8 16
3 3 6 12 24
I'd like an automated piece of code that renames column 2 to x1, column 3 to x2, and column 3 to x3. I've attempted:
for (i in 2:4){ x=colnames(z[i]); rename(z, c(x=paste("x",i,sep=""))) }
and
apply(z[,2:4], 2, function(x) rename(z, c(x=paste("x",i,sep=""))) )
but no success. Any help is much appreciated!
Upvotes: 1
Views: 3971
Reputation: 887168
You don't need a loop
names(z)[-1] <- paste0('x', 1:(ncol(z)-1))
EDIT: Added @Pierre Lafortune's suggestion
Upvotes: 4