Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace loop with one of the functions of the "apply" family

Tags:

loops

r

apply

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?

like image 963
Nicso Avatar asked Jan 14 '18 12:01

Nicso


People also ask

Which of the functions from Apply family of function is used to iterate over a list and produces the result in list?

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”).

What is the use of apply family functions in R explain in detail?

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.

Why is apply better than for loop?

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.


1 Answers

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:

  1. Transpose dataframe t(i)
  2. Perform subtraction t(i) - d
  3. Transpose it back t(t(i) - d)

So final code would be:

lapply(env, function(i) t(t(i) - d))
like image 184
pogibas Avatar answered Sep 22 '22 23:09

pogibas