Reputation: 1711
I want to rowsum some variables with the variables' name.
I tried some ways but all fail.
How can I run sum(ttt)
correctly?
Any help will be highly appreciated!
library(dplyr)
data(mtcars)
m2 = mtcars[1:3,10:11]
# Run
m2 %>%
rowwise() %>%
mutate(cc = sum(carb, gear))
# Not Run
m2 %>%
rowwise() %>%
mutate(cc = sum('carb', 'gear'))
# Not Run
ttt = c('carb', 'gear')
m2 %>%
rowwise() %>%
mutate(cc = sum(ttt))
# Run but the result was wrong
m2 %>%
rowwise() %>%
mutate(cc = sum(get(ttt)))
# Not Run
m2 %>%
rowwise() %>%
mutate(cc = sum(mget(ttt)))
Upvotes: 0
Views: 39
Reputation: 886938
We can convert to sym
bols and evaluate (!!!
)
library(dplyr)
m2 %>%
rowwise() %>%
mutate(cc = sum(!!! rlang::syms(c('carb', 'gear'))))
-output
# A tibble: 3 x 3
# Rowwise:
# gear carb cc
# <dbl> <dbl> <dbl>
#1 4 4 8
#2 4 4 8
#3 4 1 5
Or instead use rowSums
on the subset which would be vectorized and fast
m2 %>%
mutate(cc = rowSums(select(., 'carb', 'gear')))
select
can take both quoted and unquoted column names
Upvotes: 2
Reputation: 123783
You have to make use of dplyr::c_across
:
While it works without all_of
it throws a warning so using all_of
is recommended if you a vector of characters.
library(dplyr)
data(mtcars)
m2 = mtcars[1:3,10:11]
ttt = c('carb', 'gear')
m2 %>%
rowwise() %>%
mutate(cc = sum(c_across(all_of(ttt))))
#> # A tibble: 3 x 3
#> # Rowwise:
#> gear carb cc
#> <dbl> <dbl> <dbl>
#> 1 4 4 8
#> 2 4 4 8
#> 3 4 1 5
Created on 2020-12-24 by the reprex package (v0.3.0)
Upvotes: 2