I have data.frames in lists and, normally, when I want to center data, I use a loop (as seen in the example below). I would like to use some function of the "apply" family, but I can not figure out how to write the code.
An example of my data:
env <- list (data.frame(a=c(-1.08, -1.07, -1.07),
b=c( 4.61, 4.59, 4.59),
c=c( 3.46, 3.56, 3.52)),
data.frame(a=c( 3.93, 3.94, 3.92),
b=c(-6.69, -6.72, -6.68),
c=c( 3.04, 3.08, 3.03)))
The values I will use to center them:
d <- c(a=10.20, b=-10.91, c=11.89)
The type of loop that I commonly use:
for(i in 1:length(env)) {
env[[i]][, 1] <- env[[i]][, 1] - d[1]
env[[i]][, 2] <- env[[i]][, 2] - d[2]
env[[i]][, 3] <- env[[i]][, 3] - d[3]
}
Is there a way to use a function of the "apply" family to do the same thing I did in the above loop?
The lapply() function does the following simple series of operations: it loops over a list, iterating over each element in that list. it applies a function to each element of the list (a function that you specify) and returns a list (the l is for “list”).
The apply() family pertains to the R base package and is populated with functions to manipulate slices of data from matrices, arrays, lists and dataframes in a repetitive way. These functions allow crossing the data in a number of ways and avoid explicit use of loop constructs.
Use apply family for concise and efficient code. apply functions make your code smaller and more readable and you don't have to write loops so you can focus on your tasks. Whenever possible you should use apply function because there are times when it could be more efficient than a loop.
There are two things you can simplify here: looping over the list elements and subtracting every value in d
separately.
To replace for loop you can use lapply
("l" as we're iterating over the list).
# Run function for every element i in list env
lapply(env, function(i))
To simplify subtraction you can:
t(i)
t(i) - d
t(t(i) - d)
So final code would be:
lapply(env, function(i) t(t(i) - d))
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