I hope someone can help me, I have been stuck in this for a while although it does not seem so difficult to solve.
I am having some problems to copy and paste values from a data frame to another, within a loop of data frame creation.
I am using string values because I have to create many data frames.
The problem occur in the last line set(get(paste0(letters[i],"_id")), j = 1L, value = Values_df[,i])
it is copying and pasting the last column Values_df[C]
to the first column of A_id
and B_id
.
What I want instead would be the respective values of their columns in the data frame Values_df
copied to the first columns of the "id
" data frames.
Toy example:
rm(list = ls())
farms<-c("farm1","farm2","farm3","farm4")
qys<-expand.grid(c("Q1","Q2","Q3","Q4"),sprintf("Y%s", seq(1:10)))
qys<-paste(qys$Var2,qys$Var1)
basedata<-data.frame(matrix(NA,nrow=length(farms),ncol=length(qys)))
row.names(basedata)<-farms
colnames(basedata)<-qys
letters<-c("A","B","C")
Values_df<-data.frame(matrix(rexp(12, rate=.1), ncol=length(letters), nrow=length(farms)))
colnames(Values_df)<-letters
rownames(Values_df)<-farms
library(data.table)
for (i in 1:length(letters)){
assign(paste0(letters[i],"_id"),basedata)
set(get(paste0(letters[i],"_id")), j = 1L, value = Values_df[,i]) #PROBLEM
}
The desired output is:
A_id[,1]<-Values_df[,1]
B_id[,1]<-Values_df[,2]
C_id[,1]<-Values_df[,3]
but I am getting:
A_id[,1]<-Values_df[,3]
B_id[,1]<-Values_df[,3]
C_id[,1]<-Values_df[,3]