R - 按行折叠

时间:2015-07-07 22:38:30

标签: r paste collapse

我需要按行折叠数据

seq = structure(c("h", "d", "s", "s", "f", "k", "s", "s", "f", "d", 
"d", "d", "l", "l", "d", "d"), .Dim = c(4L, 4L), .Dimnames = list(
NULL, c("act1.055", "act1.056", "act1.057", "act1.058")))

我的数据如下:

     act1.055 act1.056 act1.057 act1.058
[1,] "h"      "f"      "f"      "l"     
[2,] "d"      "k"      "d"      "l"     
[3,] "s"      "s"      "d"      "d"     
[4,] "s"      "s"      "d"      "d" 

如果我这样做

paste(seq, collapse = "")
[1] "hdssfkssfdddlldd"

这不是我想要的。

我需要的是

hffl
dkdl 
ssdd 
ssdd

如果可能,在矩阵中。

2 个答案:

答案 0 :(得分:5)

matrix(apply(seq, 1, paste, collapse=''), ncol=1)
#     [,1]  
#[1,] "hffl"
#[2,] "dkdl"
#[3,] "ssdd"
#[4,] "ssdd"

答案 1 :(得分:0)

另一种选择:

matrix(do.call(paste0, data.frame(seq)))

输出:

     [,1]  
[1,] "hffl"
[2,] "dkdl"
[3,] "ssdd"
[4,] "ssdd"