[R] How to perform a calculation in each element of my list?
Erik Iverson
eiverson at NMDP.ORG
Thu Jul 23 20:42:13 CEST 2009
Mark,
My example is essentially identical to Jorge's. This is a good opportunity to compare two solutions to a problem, one using "for" loops, and one using the apply family of functions. Compare this with Daniel's solution.
## BEGIN EXAMPLE
## sample list of data.frames, different number of columns in each one
lst <- sapply(c(20, 25), function(x) as.data.frame(matrix(1:100, nrow = x)))
## define function to do what you want for one data.frame, needs at least 2 ## columns, no checks for that or for them being numeric...
mult2cols <- function(x) {
nc <- ncol(x)
x$product <- x[,nc] * x[,nc-1]
x
}
## apply the function to your list of data.frames
lst <- lapply(lst, tmp)
## END EXAMPLE
--erik
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Mark Na
Sent: Thursday, July 23, 2009 1:06 PM
To: r-help at r-project.org
Subject: [R] How to perform a calculation in each element of my list?
Hi R-helpers,
I have a list containing 10 elements, each of which is a dataframe. I wish
to add a new column to each list element (dataframe) containing the product
of the last two columns of each dataframe.
I'd appreciate any pointers, thanks!
Mark Na
[[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