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
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With