1

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

2
  • Your first line of code is a bit confusing. var_label is it from a separate package? Commented Jan 4, 2020 at 17:18
  • Yes, sorry. It is from the labelled package Commented Jan 4, 2020 at 17:21

1 Answer 1

1

We can do the rename_at

library(dplyr)
df %>%
  group_by(Q8b_1 = as_factor(Q8b_1) ) %>%
  summarise(n=n()) %>%
  na.omit() %>%
  mutate(pct = n/sum(n) * 100) %>% 
  rename_at(vars(pct), ~ l)

Or use

  rename(!! l := pct)
Sign up to request clarification or add additional context in comments.

3 Comments

The second option worked, but the first threw an error: Unknown column Research ("Research" is the value stored in l)
@erics I think the issue is because of not quoting the 'pct'. I was thinking that it is also from a stored object
@erics Ok, i think in rename_at, it should be reverse rename_at(vars(pct), ~ l)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.