dataframe - copying data from one data frame to other using variable in R -
i trying transfer data 1 data frame other. want copy 8 columns huge data frame smaller 1 , name columns n1, n2, etc..
first trying find column number need copy using this
x=as.numeric(which(colnames(old_df)=='n1_data'))
then pasting in new data frame way
new_df[paste('n',1:8,'new',sep='')]=old_df[x:x+7]
however, when run this, new 8 columns have same data. however, instead if directly use value of x, want like
new_df[paste('n',1:8,'new',sep='')]=old_df[10:17]
so questions are
- why not able use variable x. added as.numeric make sure number not list. however, not seem help.
- is there better or more efficient way achieve this?
if i'm understanding question correctly, may overthinking problem.
library(dplyr); new_df <- select(old_df, n1_data, n2_data, n3_data, n4_data, n5_data, n6_data, n7_data, n8_data); colnames(new_df) <- sub("n(\\d)_data", "n\\\\1", colnames(new_df));
Comments
Post a Comment