Jenny
Jenny

Reputation: 25

How can I store for loop results in dataframe in R

I have checked previous answers regarding to my question but my question seems to be more complicated. The following is my loop:

for(i in 2:45)
{
    abs(meta1[,i]-median(meta1[,i], na.rm=T))/(mad(meta1[,i], constant 
= 1, na.rm=T)*1.483)
}

meta1 is my data frame. I want to apply my for loop to column 2 to 45 (each is numeric vector) in my data frame. I want to store the resulting vectors in a new data frame. Could somebody point me out a direction? Thanks.

Upvotes: 0

Views: 4126

Answers (2)

akrun
akrun

Reputation: 887991

Initialize a list, store the values in each iteration in the list elements and finally cbind it to create a matrix

lst <- setNames(vector('list', 43), 2:45)
for(i in 2:45)
{
 lst[[i]] <-  abs(meta1[,i]-median(meta1[,i], na.rm=T))/(mad(meta1[,i], 
                constant = 1, na.rm=T)*1.483)
 }

do.call(cbind, lst)

Upvotes: 4

Robert Hijmans
Robert Hijmans

Reputation: 47706

You are not providing example data. That makes this guess work. But you could probably approach it like this:

meta2 <- meta1 
for(i in 2:45)
{
    meta2[,i] <- abs(meta1[,i]-median(meta1[,i], na.rm=T))/(mad(meta1[,i], constant = 1, na.rm=T)*1.483)
}

Upvotes: 2

Related Questions