[英]How do I output one vector for a matrix or dataframe in which each element is a string concatenated from each row?
I have a matrix (or dataframe):我有一个矩阵(或数据框):
m1 <- matrix(letters[1:8], ncol = 2, byrow=TRUE)
[,1] [,2]
[1,] "a" "b"
[2,] "c" "d"
[3,] "e" "f"
[4,] "g" "h"
Desired output:所需的 output:
vec1 = c("ab", "cd", "ef", "gh")
I would prefer this would work for a matrix of any column or row size.我希望这适用于任何列或行大小的矩阵。 Base R and dplyr appreciated.
基地 R 和 dplyr 赞赏。
We can either convert to data.frame
and then paste
with do.call
我们可以转换为
data.frame
然后用do.call
paste
do.call(paste, c(as.data.frame(m1), sep=''))
#[1] "ab" "cd" "ef" "gh"
Or a less efficient option is apply
或者
apply
效率较低的选项
apply(m1, 1, paste, collapse = '')
With tidyverse
, we can use reduce
with str_c
使用
tidyverse
,我们可以使用reduce
和str_c
library(dplyr)
library(purrr)
library(stringr)
as_tibble(m1) %>%
reduce(str_c, sep="")
#[1] "ab" "cd" "ef" "gh"
Or if there are only two column, extract the columns by index and use paste0
或者如果只有两列,则按索引提取列并使用
paste0
paste0(m1[,1], m1[,2])
Or with asplit
, split the matrix by column into a list
of vector
s and then use do.call
或使用
asplit
,将矩阵按列拆分为vector
list
,然后使用do.call
do.call(paste, c(asplit(m1, 2), sep=''))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.