I have following type of data, although data.frame is very large.
A1 <- c("A/B", "A/A", "B/B", "A/A")
B1 <- c("B/B", "C/C", "C/B", "D/A")
C1 <- c("B/B", "C/C", "C/B", "D/A")
mydf <- data.frame (A1, B1, C1)
mymat <- as.matrix (mydf)
mymat
A1 B1 C1
[1,] "A/B" "B/B" "B/B"
[2,] "A/A" "C/C" "C/C"
[3,] "B/B" "C/B" "C/B"
[4,] "A/A" "D/A" "D/A"
I want split each columns into two "/" is sperator. Thus output would look like:
A1a A1b B1a B1b C1a C1b
[1,] A B B B B B
[2,] A A C C C C
[3,] B B C B C B
[4,] A A D A D A
Here's a mildly devious way. Add "/"'s between the characters and read in with that as separator:
splitdf <- read.table(text=capture.output(write.table(mydf, quote=FALSE,
sep="/",col.names=FALSE,row.names=FALSE)),
sep="/")
names(splitdf) <- paste( rep(names(mydf), each=2), c("a","b"), sep="")
splitdf
#------------
A1a A1b B1a B1b C1a C1b
1 A B B B B B
2 A A C C C C
3 B B C B C B
4 A A D A D A
Here's one solution using reshape2's colsplit:
require(reshape2)
mymat <- as.data.frame(mymat)
LS <- lapply(seq_along(mymat), function(i){
colsplit(mymat[, i], "/", paste0(colnames(mymat)[i], letters[1:2]))
}
)
do.call('cbind', LS)
Which yields:
A1a A1b B1a B1b C1a C1b
1 A B B B B B
2 A A C C C C
3 B B C B C B
4 A A D A D A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With