[R] how to loop thru a matrix or data frame , and append calculations to a new data frame?
David Winsemius
dwinsemius at comcast.net
Sat Oct 31 19:00:52 CET 2009
On Oct 31, 2009, at 12:33 PM, John Kane wrote:
> 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
It would have been much more compact (and in the spirit of functional
programming) to just do:
mp5data <- mydata*5
# binary operations applied to dataframes give sensible results when
the data types allow.
mp5data
aa bb
[1,] 5 55
[2,] 10 60
[3,] 15 65
[4,] 20 70
[5,] 25 75
Many times the loops are implicit in the vectorized design of R. And
that solution would not result in the structure requested, for which
some further "straightening" would be needed:
> mp5data <- as.vector(as.matrix(mydata)*5)
> mp5data
[1] 5 10 15 20 25 55 60 65 70 75
-- David
>
> 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.
>>
>
> ______________________________________________
> 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.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list