Say I have the following data:
df <- structure(list(treat = structure(1:4, levels = c("Control", "Alexander Hamilton",
"Politicians pay attention", "Mark your calendar"), class = "factor"),
female_n = c(314709L, 10456L, 10481L, 10455L), female_mean = c(0.506,
0.506, 0.504, 0.5), female_sd = c(0.5, 0.5, 0.5, 0.5), birth_year_n = c(314709L,
10456L, 10481L, 10455L), birth_year_mean = c(1973.74, 1973.654,
1973.486, 1973.766), birth_year_sd = c(16.867, 16.997, 16.869,
16.89), provided_phone_no_n = c(314709L, 10456L, 10481L,
10455L), provided_phone_no_mean = c(0.656, 0.666, 0.663,
0.647), provided_phone_no_sd = c(0.475, 0.472, 0.473, 0.478
), dem_n = c(314709L, 10456L, 10481L, 10455L), dem_mean = c(0.48,
0.474, 0.482, 0.478), dem_sd = c(0.5, 0.499, 0.5, 0.5), rep_n = c(314709L,
10456L, 10481L, 10455L), rep_mean = c(0.136, 0.141, 0.142,
0.138), rep_sd = c(0.343, 0.348, 0.349, 0.345), uaf_n = c(314709L,
10456L, 10481L, 10455L), uaf_mean = c(0.363, 0.365, 0.357,
0.363), uaf_sd = c(0.481, 0.481, 0.479, 0.481)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -4L))
I want to add in a new *_se
column which takes as inputs the existing *_n
and *_sd
columns for each of the variable groups in my data. I.e. one for each of female_*
, birth_year_*
, provided_phone_no_*
, dem_*
, rep_*
, and uaf_*
.
Attempting to do this, I think mutate(across())
is probably the right helper function, but i’m having some issues substringing {.col}
and getting R to recognise it as a column name. This is my attempt so far:
df %>%
mutate(
across(ends_with("_sd"),
list(
se = ~.x / sqrt(!!ensym("{str_replace(.col, '_sd', '_n')}"))
)
)
The above returns the error:
Error in `ensym()`:
! `arg` must be a symbol
Backtrace:
1. ... %>% ...
10. rlang::abort(message = message)
Can anyone see where i’m going wrong here?