Same function over multiple data frames in R

前端 未结 4 1456
南笙
南笙 2020-11-29 03:08

I am new to R, and this is a very simple question. I\'ve found a lot of similar things to what I want but not exactly it. Basically I have multiple data frames and I simply

4条回答
  •  野性不改
    2020-11-29 03:36

    Put them into a list and then run rowMeans over the list.

    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])
    
    lapply(list(df1, df2), function(w) { w$Avg <- rowMeans(w[1:2]); w })
    
     [[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
    

提交回复
热议问题