简体   繁体   English

我如何 output 一个矩阵向量或 dataframe ,其中每个元素都是从每一行连接的字符串?

[英]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 ,我们可以使用reducestr_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.

相关问题 为向量中的每个元素在数据框中创建行 - Creating row in dataframe for each element in vector 如何在数据框的每一行上执行一个函数,并将该输出的一个元素作为该行中的新列插入 - How do I perform a function on each row of a data frame and have just one element of the output inserted as a new column in that row 为向量的每个元素做我只为 R 中的一个元素做的事情 - Do for Each Element of a Vector What I Do for Just One in R 在 R 中,从 dataframe 的每一行中减去一个向量 - In R subtract a vector from each row of a dataframe 如何在每个向量的迭代中将函数应用于矩阵 - How do i apply function into matrix in iteration for each vector 如何在数据框的一行中将字符串与向量的每个元素连接起来? - How can I concatenate a string with each element of a vector within a row of a data frame? 将 dataframe 矩阵的每一行除以 R 中长度较短的向量? - Dividing each row of a dataframe matrix by a vector with a shorter length in R? 从R中矩阵的每一行中选择一个元素 - Select an element from each row of a matrix in R 将 dataframe 的每一行中的每个元素除以 R 中的一行中的值 - Divide each element in each row of a dataframe by the value in one of the rows in R R:如何从列表的每个内部元素中删除第一个元素而不将其转换为矩阵? - R: How do I remove the first element from each inner element of a list without converting it to matrix?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM