I would like to use the values of this sequence seq
to rename the columns x1
to x10
of the data frame df
.
the sequence - variable names to be used
var_names<-seq(10, 23.5, 1.5)
the data frame, where all variables beginning with x
are to be renamed by the values of the sequence var_names
df =
data.frame( x1 = rlnorm(10000), x2 = rlnorm(10000), x3 = rlnorm(10000), x4 = rlnorm(10000), x5 = rlnorm(10000), x6 = rlnorm(10000), x7 = rlnorm(10000), x8 = rlnorm(10000), x9 = rlnorm(10000), x10 = rlnorm(10000))
my attempt
df_renamed <- apply(df, 2, function(x) data.table::setnames(df, old=colnames(x), new=var_names))
## Error in data.table::setnames(df, old = colnames(x), new = var_names) :
## 'new' is not a character vector
expected output
In the output dataframe I want to replace the variable names x1 by 10, x2 by 11.5, x3 by 13, x4 by 14.5, x5 by 16, x6 by 17.5, x7 by 19, x8 by 20.5, x9 by 22, x10 by 23.5.
While this replacement of the variable names can be done individually using this and other approaches when there are only a few columns, I want a function that does the job efficiently with large datasets using directly the sequence var_names
and taking advantage of the fact that all variables to be renamed begin with x
.
colnames(df) <- var_names
? - Clemsangdata.table::setnames(df, var_names)
- David Arenburg