Reputation: 820
Instead of explicitly stating the column names in a mutate call, I want to do so dynamically from a list of names generated elsewhere. I tried something along these lines:
df <- data.frame(x=1:10, y=21:30)
l <- c('x', 'y')
get_from_df <- function(x) { get(pos=df,x) }
df %>% rowwise %>% mutate(presum=do.call(sum, map(l, get_from_df)))
It gives the sum for the whole data.frame, 310, not the row sums. output is:
df %>% rowwise %>% mutate(presum=do.call(sum, map(l, get_from_df)))
# A tibble: 10 x 3
# Rowwise:
x y presum
<int> <int> <int>
1 1 21 310
2 2 22 310
3 3 23 310
4 4 24 310
5 5 25 310
6 6 26 310
7 7 27 310
8 8 28 310
9 9 29 310
10 10 30 310
I ended up back without rowwise using rowSum instead.
df %>% mutate(presum=rowSums(do.call(cbind, map(l,f)) ))
It works, but I'd like to understand better what rowwise is doing under the covers and what limitations I ran into. Is there anywhere that describes this before I make time to read some code?
Upvotes: 1
Views: 53
Reputation: 7116
Perhaps this is what you looking for?
Note the use of c_across
and all_of
from tidy selection.
library(tidyverse)
df <- data.frame(x=1:10, y=21:30)
l <- c('x', 'y')
get_from_df <- function(x) { get(pos=df,x) }
#df %>% rowwise %>% mutate(presum=do.call(sum, map(l, get_from_df)))
df %>%
rowwise() %>%
mutate(presum = sum(c_across(all_of(l))))
#> # A tibble: 10 × 3
#> # Rowwise:
#> x y presum
#> <int> <int> <int>
#> 1 1 21 22
#> 2 2 22 24
#> 3 3 23 26
#> 4 4 24 28
#> 5 5 25 30
#> 6 6 26 32
#> 7 7 27 34
#> 8 8 28 36
#> 9 9 29 38
#> 10 10 30 40
Created on 2021-11-24 by the reprex package (v2.0.1)
Upvotes: 1