简体   繁体   English

如何将数字向量列表转换为具有公共前缀的文本向量列表?

[英]How to convert a list of numeric vectors to a list of text vectors with a common prefix?

So I have a list of numeric vectors, and I need to convert it to a similar list of character "strings", each with a common prefix. 因此,我有一个数字矢量列表,并且需要将其转换为类似的字符串“ strings”列表,每个字符串都有一个公共前缀。

So I start out simple: 所以我开始很简单:

> aNumVect = c(1,2,3,4,5,6)
> aNumVect
[1] 1 2 3 4 5 6
> paste(sep="", "X", aNumVect)
[1] "X1" "X2" "X3" "X4" "X5" "X6"
> 

Ah, perfect! 啊,完美! Exactly what I need. 正是我所需要的。 Except I need to do it to a list of numeric vectors: 除了我需要对数字矢量列表进行处理外:

> aListOfNumVects = list(c(1,2,3,4,5,6), c(7,8,9,10,11,12))
> aListOfNumVects
[[1]]
[1] 1 2 3 4 5 6

[[2]]
[1]  7  8  9 10 11 12

> paste(sep="", "X", aListOfNumVects)
[1] "Xc(1, 2, 3, 4, 5, 6)"    "Xc(7, 8, 9, 10, 11, 12)"

OK, no, that is NOT what I need. 好,不,那不是我所需要的。 I need the result to look like this: 我需要结果看起来像这样:

[[1]]
[1] "X1" "X2" "X3" "X4" "X5" "X6"

[[2]]
[1]  "X7"  "X8"  "X9" "X10" "X11" "X12"

How can I get that, short of manually looping & converting the list one vector at a time? 如果没有一次手动循环并转换一个向量列表,我该如何得到呢? Which, by the way, isn't too difficult.... 顺便说一句,这并不难。

> XprefixedListOfNumVects = list()
> for (i in 1:length(aListOfNumVects))
+    XprefixedListOfNumVects[[i]] = paste(sep="", "X", aListOfNumVects[[i]])
> XprefixedListOfNumVects
[[1]]
[1] "X1" "X2" "X3" "X4" "X5" "X6"

[[2]]
[1] "X7"  "X8"  "X9"  "X10" "X11" "X12"

....but I know there's gotta be a smarter way. ....但我知道一定有更聪明的方法。

You can use lapply() , which applies a function to each element of a list: 您可以使用lapply() ,该函数将函数应用于列表的每个元素:

lapply(aListOfNumVects, function(y) paste0("X", y))
[[1]]
[1] "X1" "X2" "X3" "X4" "X5" "X6"

[[2]]
[1] "X7"  "X8"  "X9"  "X10" "X11" "X12"

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

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