merge - rename the multiple columns in R -
i have 1000 files column similar column names.for example :
df1
date price close
df2
date price close
and on...
if try merge them based date merge columns have retained old names , want rename them in loop
so merge data set looks
date price close price close
i want like
date price1 close1 price2 close2.
is there easy way it? have tried couple of things not giving me correct output
this using plyr package:
mod_join = function(mypath){ filenames=list.files(path=mypath, full.names=true) datalist = lapply(filenames, function(x){read.csv(file=x,header=t)[,c('date','high','low')]}) join_all(datalist,by = "date") }
this using merge command on data frame:
merge2 = function(mypath){ filenames=list.files(path=mypath, full.names=true) datalist = lapply(filenames, function(x){read.csv(file=x,header=t)[,c('date','high','low')]}) reduce(function(x,y) {merge(x,y,by.x= "date",by.y = "date",all=t)}, datalist)} }
i tried using loop making data frame lead using each data frame subset , merge subsequently somehow not subsetting dataframes:
for (i in 1:1000){ data_subset <- sprintf('data_%d',i) mydata_subset <- data.frame(,data_subset["date"],data_subset["high"],data_subset["daylow"]) obj_name <- paste('subset_pricedata',i,sep ="_") assign(obj_name,value = mydata_subset) }
any great. thanks
hopefully, job:
library(plyr) df1 = rename(df1,c("price"="price1","close"="close1")) df2 = rename(df2,c("price"="price2","close"="close2")) new = merge(df1,df2,all=true)
please comment if face difficulties.
Comments
Post a Comment