I'm having trouble with the following in R using dplyr and separate. I have a dataframe like this:
x<-c(1,2,12,31,123,2341)
df<-data.frame(x)
and I'd like to split each digit into its constituent parts and create a new variable for each into the dataframe, like so:
x a b c d
1 1
2 2
3 12 1 2
4 31 3 1
5 123 1 2 3
6 2341 2 3 4 1
I have tried:
df <- df |>
mutate(x = as.character(x))|>
separate(x, c("a", "b", "c", "d"), sep=1, remove=F)
but I get:
Error in names(out) <- as_utf8_character(into) :
'names' attribute [4] must be the same length as the vector [2]
l = sapply(as.character(x), strsplit, split=''); list2DF(lapply(l, `length<-`, max(lengths(l))))would be a simple option. Orcbind(x, do.call('rbind', lapply(l, `length<-`, max(lengths(l)))))to match your desired format. Efficient ways might be viaread.fwf,textConnectionorscan-- haven't thought about it.