0

I would like to split a character field into individual variables, one for each character in a string.

library(dplyr)
temp1 <- data.frame(a = c('dedefdewfe' , 'rewewqreqw'))


for(i in 1:10){

  temp1 <- temp1 %>% 
    mutate(paste('v' , i , ,sep = '') = substr(a , i , i))
}

The resulting dataframe would have 11 variables, the original a , v1 through v10

1 Answer 1

3

tidyr::separate is good for this. You can't split on an empty string, but you can specify splitting positions ...

library(tidyr)
library(dplyr)
temp1 %>% 
  mutate(b=a) %>%   ## make a copy
  separate(b,into=paste0("v",1:10),sep=1:9)

(probably better practice to use nc <- nchar(temp1$a[1]) and then use nc, nc-1 instead of 10, 9 respectively)

Sign up to request clarification or add additional context in comments.

1 Comment

you might want to consider editing your title to something like "split a character column of a data frame into multiple columns" - i.e., make it about what you're trying to accomplish rather than the particular approach

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.