Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid for loops by apply - worth the trouble?

Tags:

r

I wrote a Rscript to bring some data in a desired format. In particular I just want to rearrange the dataset to finally have it in a format of 8 rows and 12 columns (96-well plate format). I nested two for loops which works perfectly fine:

element1 = seq(1,96,1)
element2 = seq(0.5,48,0.5)
df = data.frame(element1,element2)
storage = data.frame(matrix(NA,nrow = 8, ncol = 12))
container = vector("list",ncol(df))

for (n in 1:ncol(df)){
      j = 0  
        for (i in seq(1,length(df[,n]),12)) { 
              j = j+1
              storage[j,] = df[(i):(i+11),n]  
          }
     container[[n]]=storage

}

Remark: I packed the data in a list for easier exporting in .xls
And I know that this is a really unsophisticated approach...but it works

I am however willing to learn :-) as I read lot one should avoid for loops and use "apply" in combination with functions instead. I tried to solve the task by using apply and functions. However I was not able to get the result and the usage of functions and apply seemed much more complex to me. So is it always worth to avoid for loops? If yes, how would you do it?

Thanks, Christian

like image 975
ChriiSchee Avatar asked Mar 18 '23 12:03

ChriiSchee


1 Answers

You appears to just be reshaping each column to a matrix. How about just

container <- lapply(df, matrix, byrow=T, ncol=12)

if you really need a data.frame, try

container <- lapply(df, function(x) data.frame(matrix(x, byrow=T, ncol=12)))
like image 139
MrFlick Avatar answered Mar 20 '23 15:03

MrFlick