r - How should one pass columns as variables or indexes to tidyr::separate -


getting errors while trying pass columnames indexes or variables tidyr::separate.

setting libraries & data:

library(tidyr) library(dplyr) x <- data.frame(col1 = 1:4,                 col2 = c("a,b,c","d,e,f","g,h,i","j,k,l")) sep <- "," colnamevar <- "col2" 

these work (in dplyr):

x %>% select(col2) %>% names # [1] "col2" x %>% select(colnamevar %>% as.name %>% eval) %>% names # [1] "col2" x %>% select(2) %>% names # [1] "col2" 

as (with separate):

x %>%  separate(col2,  paste("col2",1:3,sep="."),  sep = sep) %>% names # [1] "col1"   "col2.1" "col2.2" "col2.3" 

but fails:

x %>%  separate(colnamevar %>% as.name %>% eval,  paste("col2",1:3,sep="."),  sep = sep) %>% names 

error: invalid column specification

as this:

x %>%  separate(2,  paste("col2",1:3,sep="."),  sep = sep) %>% names 

error: invalid column specification

how should done?

using underscore version of separate, can pass strings:

# colnames predefined string x %>%   separate_(colnamevar, paste("col2", 1:3, sep = "."), sep = sep) %>%   names # [1] "col1"   "col2.1" "col2.2" "col2.3"  # colnames index (well almost, getting colname string index) x %>%   separate_(colnames(x)[2], paste("col2", 1:3, sep = "."), sep = sep) %>%   names # [1] "col1"   "col2.1" "col2.2" "col2.3" 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -