1

The following is an example of a question that has been asked several times in the past, but I have not seen a fully satisfactory answer. I would like to know if newer strategies have been developed, or if there is no convenient way to get to the desired result.

The typical question asks if a function can be applied to several data frames. An example is:

df1 <- data.frame(x = rep(3, 5), y = seq(1, 5, 1), ID = letters[1:5])

df2 <- data.frame(x = rep(5, 5), y = seq(2, 6, 1), ID = letters[6:10])

Above are the two (of perhaps a long list of) data frames, and what is desired is to add another column to each of the original dataframes which displays the average of that row. A typical answer is:

lapply(list(df1, df2), function(w) { w$Avg <- rowMeans(w[1:2]); w })

However, this does not change or add a column to the original data frames, but produces the following:

 [[1]]
   x y ID Avg
 1 3 1  a 2.0
 2 3 2  b 2.5
 3 3 3  c 3.0
 4 3 4  d 3.5
 5 3 5  e 4.0

 [[2]]
   x y ID Avg
 1 5 2  f 3.5
 2 5 3  g 4.0
 3 5 4  h 4.5
 4 5 5  i 5.0
 5 5 6  j 5.5

Question: Is there a procedure to apply a function to many data frames in a way that changes those dataframes directly?

I looked at many questions and answers, but they were basically the above strategy. Here is one example: Same function over multiple data frames in R

3
  • 1
    Does this solve your question? Using lapply() or map() and then list2env(): stackoverflow.com/questions/60076245/… Commented Dec 9, 2024 at 16:10
  • 1
    If you have a bunch of data frames of similar structure you should almost certainly be keeping them in a list, not putting them into the list for a single modification. If you have list_df = list(df1, df2) then you do list_df = lapply(list_df, ...) then the data frames in your list will be modified. Commented Dec 9, 2024 at 16:20
  • Harrison's reference worked great! I think it used the strategy that Gregor mentioned. Commented Dec 9, 2024 at 23:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.