u31889
u31889

Reputation: 351

Convert a vector of character strings as symbols

How could one convert a vector of strings into symbols for passing into tidyverse?

An example that works by hardcoding the colnames:

df <- data.frame(col1=c("A","B"), col2=c("C", "D"), col3=c("E", "F"), stringsAsFactors=F)
df
  col1 col2 col3
1    A    C    E
2    B    D    F

df %>% complete(nesting(col1, col2), col3)
  col1  col2  col3 
1 A     C     E    
2 A     C     F    
3 B     D     E    
4 B     D     F  

However using a vector of colnames does not work.

vec <- c("col1", "col2")

df %>% complete(nesting(vec), col3)
Error: Join columns must be present in data.
x Problem with `vec`.

df %>% complete(nesting(get(vec)), col3)
Error: Join columns must be present in data.
x Problem with `vec`.

# no error but would like to avoid to use 'fill()' after
df %>% complete(nesting(!!as.symbol(vec)), col3)
  col1  col3  col2 
1 A     E     C    
2 A     F     NA   
3 B     E     NA   
4 B     F     D  

df %>% complete(nesting(!!sym(vec)), col3)
Error: Only strings can be converted to symbols

df %>% complete(nesting(vars(!!as.symbol(vec)), col3))
Error: Join columns must be present in data.
x Problem with `vars(col1)`.

Upvotes: 0

Views: 1724

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

You need to

  1. convert the character strings to names
  2. unquote-splice them via !!!
df %>% complete(nesting(!!! rlang::syms(vec)), col3)

Upvotes: 3

u31889
u31889

Reputation: 351

Actually, the last thing I did not try...

df %>% complete(nesting(.[which(names(.) %in% vec)]), col3)
  col1  col2  col3 
1 A     C     E    
2 A     C     F    
3 B     D     E    
4 B     D     F  

Upvotes: 0

Related Questions