Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201977

r - pass string stored in variable in dplyr function

$
0
0

I want to supply a string stored in a variable as a new column name while performed a dplyr group_by function. How can I retrieve the value stored inside the variable, and not the name of the variable, as a string?

# store label name
l <- var_label(df$Q8b_1)

# group variable and supply label to new column based on mutate
# DOES NOT WORK
df %>%
  group_by( as_factor(Q8b_1) ) %>%
  summarise(n=n()) %>%
  na.omit() %>%
  mutate(pct = n/sum(n) * 100) %>% 
  rename(l = pct) %>% # use label inside l, not literal "l"

# result
 as_factor(Q8b_1)   n           l
                1 252  38.4732824
                2 261  39.8473282
                3 112  17.0992366
                4  25   3.8167939
                5   5   0.7633588
            Total 655 100.0000000


Viewing all articles
Browse latest Browse all 201977

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>