[R] How to apply five lines of code to ten dataframes?
baptiste auguie
baptiste.auguie at googlemail.com
Mon Dec 7 16:16:10 CET 2009
Hi,
You could define a function that does the calculations for a given
data.frame and apply it to all your data.frames,
d1 <- data.frame(a=1:10, b=rnorm(10))
d2 <- data.frame(a=-(1:10), b=rnorm(10))
calculations <- function(d){
if(is.character(d)) d <- get(d)
transform(d,
c = a^2,
d = d[, 1] + d$b)
}
calculations(d1)
lapply(paste("d", 1:2, sep=""), calculations)
HTH,
baptiste
2009/12/7 Mark Na <mtb954 at gmail.com>:
> Hello R-helpers,
>
> I have 10 dataframes (named data1, data2, ... data10) and I would like to
> add 5 new columns to each dataframe using the following code:
>
> data1$LogDepth<-log10(data1[,2]/data1[,4])
> data1$LogArea<-log10(data1[,3]/data1[,5])
> data1$p<-2*data1[,6]/data1[,7]
> data1$Exp<-data1[,2]^(2/data1[,8])
> data1$s<-data1[,3]/data1[,9]
>
> ...but I would prefer not to repeat this chunk of code 10 times!
>
> I have struggled with setting up a loop to apply these 5 lines of code to
> each of the 10 dataframes, but I'm not having much luck.
>
> Any help would be much appreciated.
>
> Thank you, Mark
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list