Reputation: 33
I have a list of dataframes list1
and need a new column 'mn' in each dataframe that is the mean of a conditional number of columns based on the value in another column num
plus one. So, for num=3
the new column would be the mean of the first four columns. For the example below
df1 <- data.frame(num= c(3, 1, 1, 1, 2), d1= c(1, 17, 17, 17, 15), d2= c(1, 15, 15, 15, 21), d3= c(6, 21, 21, 21, 23), d4= c(2, 3, 3, 3, 2))
df2 <- data.frame(num= c(3, 2, 2, 2, 2), d1= c(1, 10, 10, 10, 15), d2= c(1, 5, 5, 5, 21), d3= c(6, 2, 2, 2, 23), d4= c(2, 3, 3, 3, 5))
list1 <- list(df1, df2)
I would expect
newlist
[[1]]
num d1 d2 d3 d4 mn
1 3 1 1 6 2 2.5
2 1 17 15 21 3 16.0
3 1 17 15 21 3 16.0
The closest I've gotten is
newlist <- lapply(list1, function(x) {
x <- cbind(x, sapply(x$num, function(y) {
y <- rowSums(x[2:(2+y)])/(y+1)
}))
})
which binds columns for the means of every row. Based on this post I think I need a seq_along or maybe a Map on the inside function but I can't figure out how to implement it.
Upvotes: 1
Views: 94
Reputation: 887511
An option is to loop over the list
with lapply
, extract the number of elements for each row with apply
based on the 'num' column value (+1), get the mean
and create the new column in transform
lapply(list1, function(x) transform(x,
mn = apply(x, 1, function(y) mean(y[-1][seq(y[1]+1)]))))
#[[1]]
# num d1 d2 d3 d4 mn
#1 3 1 1 6 2 2.50000
#2 1 17 15 21 3 16.00000
#3 1 17 15 21 3 16.00000
#4 1 17 15 21 3 16.00000
#5 2 15 21 23 2 19.66667
#[[2]]
# num d1 d2 d3 d4 mn
#1 3 1 1 6 2 2.500000
#2 2 10 5 2 3 5.666667
#3 2 10 5 2 3 5.666667
#4 2 10 5 2 3 5.666667
#5 2 15 21 23 5 19.666667
Or with tidyverse
, by pivoting to 'long' format with pivot_longer
, do a group by row and get the mean
of the first 'n' elements based on the 'num' value
library(purrr)
library(dplyr)
library(tidyr)
map(list1, ~
.x %>%
mutate(rn = row_number()) %>%
pivot_longer(cols = starts_with('d')) %>%
group_by(rn) %>%
summarise(value = mean(value[seq_len(first(num) + 1)])) %>%
pull(value) %>%
bind_cols(.x, mn = .))
Upvotes: 1