[R] Adding Column to Data Frames Using a Loop
Sparks, John James
jspark4 at uic.edu
Wed May 1 18:53:23 CEST 2013
Dear R Helpers,
I am trying to do calculations on multiple data frames and do not want to
create a list of them to go through each one. I know that lists have many
wonderful advantages, but I believe the better thing is to work df by df
for my particular situation. For background, I have already received some
wonderful help on how to handle some situations, such as removing columns:
x=as.data.frame(matrix(c(1,2,3,
1,2,3,
1,2,2,
1,2,2,
1,1,1),ncol=3,byrow=T))
y=as.data.frame(matrix(c(1,2,3,
1,2,3,
1,2,2,
1,2,2,
1,1,1),ncol=3,byrow=T))
z=as.data.frame(matrix(c(1,2,3,
1,2,3,
1,2,2,
1,2,2,
1,1,1),ncol=3,byrow=T))
for(i in letters[24:26] ) assign( i, subset(get(i), select=-c(V1)) )
x
y
z
And I figured how to do further processing using functions:
myfunc<-function(DF){
DF$V4<-DF$V2+DF$V3
return(DF)
}
for(i in letters[24:26] ) assign( i, myfunc(get(i)))
But if I want to do a rather simple calculation and store it as a new
column in each data frame such as
x$V4<-x$V2+x$V3
y$V4<-y$V2+y$V3
z$V4<-z$V2+z$V3
is there a simpler way to do this than building a function as shown above?
I tried a few variations of
i<-24
assign(paste(i,"$V4",sep=""),paste(get(i),"$V2+",get(i),"$V3",sep=""))
but keep getting syntax errors.
If anyone could help with the syntax as to how to accomplish the
calculation above without building a function, I would really appreciate
it.
--John Sparks
More information about the R-help
mailing list