我有一个看起来像的矩阵:
1 2 3
1 part of a text1
2 part of a text2
3 part of a text3
我需要一个来自它的矢量:
c("part of a text1","part of a text 2","part of a text3"
)
感谢您的帮助!
答案 0 :(得分:4)
你可以试试这个
apply(df, 1, paste0, collapse=" ")
[1] "part of a text1" "part of a text2" "part of a text3"
答案 1 :(得分:3)
我会在转换'矩阵后使用do.call(paste
。到data.frame
,因为对于> 1e6行的大数据集来说会更快。话虽如此,并非每个数据集都是一个大数据集......
do.call(paste, as.data.frame(m1))
#[1] "part of a text1" "part of a text2" "part of a text3"
如果列数较少,例如3,则即使手动指定列并使用sprintf
或paste
,也会非常快。
sprintf('%s %s %s', m1[,1] , m1[,2], m1[,3])
#[1] "part of a text1" "part of a text2" "part of a text3"
m2 <- m1[rep(1:nrow(m1), 1e6),]
system.time(do.call(paste, as.data.frame(m2)))
# user system elapsed
# 2.873 0.000 1.816
system.time(apply(m2, 1, paste0, collapse=' '))
# user system elapsed
#23.486 0.000 20.441
system.time(sprintf('%s %s %s', m2[,1], m2[,2], m2[,3]))
# user system elapsed
#1.492 0.000 1.262
system.time(paste(m2[,1], m2[,2], m2[,3]))
# user system elapsed
# 1.245 0.000 1.051
m1 <- structure(c("part", "part", "part", "of a", "of a", "of a",
"text1",
"text2", "text3"), .Dim = c(3L, 3L), .Dimnames = list(c("1",
"2", "3"), c("X1", "X2", "X3")))