我有以下类型的数据,尽管 data.frame 非常大。
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"
我想将每一列分成两个“/”是sperator。因此输出看起来像:
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
最佳答案
这是使用 reshape2 的 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)
其中产生:
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