简体   繁体   English

将存储在向量中的所有字符串粘贴到单个字符串中,这适用于列表中的每个字符串向量

[英]Paste all strings stored in a vector into a single string, this for each string vectors in a list

This is the begining of the sample code : 这是示例代码的开头:

library(stringr)

Sentences_vector1 <- as.data.frame(rbind("toto a titi", "tata c m tztz itutu", "toto z titi l k tutu h tyty"), stringsAsFactors=F)
Sentences_vector2 <- as.data.frame(rbind("toto a titi", "tata c m tztz itutu", "toto z titi l k tutu h tyty"), stringsAsFactors=F)
Sentences_vectors <- cbind(Sentences_vector1, Sentences_vector2)

List_with_diff_nb_strings = str_match_all(Sentences_vectors$V1, "[a-zA-Z]{2,}")

And now, I'm trying to paste all strings stored in a vector into a single string, this for each string vectors in a list. 现在,我试图将存储在向量中的所有字符串粘贴到单个字符串中,该字符串用于列表中的每个字符串向量。 Please note that the vectors have different lengths. 请注意,向量的长度不同。

List_concacenated_strings = sapply(List_with_diff_nb_strings,function (x) base::paste(x, sep = " "))

Thus, I would like to get a result with a content similar as this one : 因此,我想得到一个内容与此类似的结果:

list(c("toto titi"), c("tata tztz tutu"), c("toto titi tutu tyty"))

... but it doesn't work since I cannot specify the columns as their numbers are different for each line (character vectors with different lengths) of the list. ...但是它不起作用,因为我无法指定列,因为列表的每一行(具有不同长度的字符向量)的列号都不同。

Maybe it's due to the fact that in my true R code, the command : 也许是由于在我真正的R代码中,命令:

str(List_with_diff_nb_strings[[3]])

returns : 返回:

chr [1:4, 1] "toto" "titi" "tutu" "tyty"

instead of a "simple" vector like this : 而不是像这样的“简单”向量:

chr [1:4] "toto" "titi" "tutu" "tyty"

Can anybody help me? 有谁能够帮助我? Thanks in advance. 提前致谢。

Replace the respective line of code with the following: 用以下代码替换相应的代码行:

List_concacenated_strings = as.list(sapply(List_with_diff_nb_strings,function (x) base::paste(x, sep = " ",collapse=" ")))

And you get your desired output: 您将获得所需的输出:

[[1]]
[1] "toto titi"

[[2]]
[1] "tata tztz tutu"

[[3]]
[1] "toto titi tutu tyty"

PS: This should be on Stack Overflow PS:这应该在堆栈溢出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM