Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

r - 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)`.
question from:https://stackoverflow.com/questions/65921972/convert-a-vector-of-character-strings-as-symbols

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...