harsh harsh - 3 months ago 18
R Question

How to put array having spaced values in a data frame?

I am trying to split a series of numbers into digits. I have splitted the digits using strsplit. The dataset that I have after splitting is like -

strings <- c("001", "002", "003", "004")
dataset <- strsplit(strings, split="")
dataset

[[1]]
[1] "0" "0" "1"

[[2]]
[1] "0" "0" "2"

[[3]]
[1] "0" "0" "3"

[[4]]
[1] "0" "0" "4"


Now , I want to put this into a data frame so that each number comes in a separate column for all values in the array.
Like this -

## V1 V2 V3
## 0 0 1
## 0 0 2
## .
## .


Any suggestions how to do this?

Answer

You can use ldply from the plyr package

library(plyr)

ldply(strsplit(as.character(dataset),split=""))

##    V1 V2 V3
## 1   0  0  1
## 2   0  0  2
## 3   0  0  3
## 4   0  0  4
## 5   0  0  5
## 6   0  0  6
## 7   0  0  7
## 8   0  0  8
## 9   0  0  9
## 10  0  1  0
## 11  0  1  1
## 12  0  1  2
## 13  0  1  3