[R] how to loop thru a matrix or data frame , and append calculations to a new data frame?
John Kane
jrkrideau at yahoo.ca
Sat Oct 31 17:33:12 CET 2009
Do you mean to apply the same calculation to each element?
? apply
mydata <- data.frame(aa = 1:5, bb= 11:15)
mp5 <- function(x) x*5
mp5data <- apply(mydata, 2, mp5)
mp5data
This is functionally equivelent to a double if loop.
mydata <- data.frame(aa = 1:5, bb= 11:15)
newdata <- data.frame(matrix(rep(NA,10), nrow=5))
for (i in 1:length(mydata[1,])) {
for (j in 1:5) {
newdata[j,i] <- mydata[j,i]*5
}
}
newdata
--- On Fri, 10/30/09, Robert Wilkins <robstdev at gmail.com> wrote:
> From: Robert Wilkins <robstdev at gmail.com>
> Subject: [R] how to loop thru a matrix or data frame , and append calculations to a new data frame?
> To: r-help at r-project.org
> Received: Friday, October 30, 2009, 11:46 AM
> How do you do a double loop through a
> matrix or data frame , and
> within each iteration , do a calculation and append it to a
> new,
> second data frame?
> (So, if your original matrix or data frame is 4 x 5 , then
> 20
> calculations are done, and the new data frame, which had 0
> rows to
> start with, now has 20 rows)
>
> ______________________________________________
> 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