所以我有一个数字向量列表,我需要将它转换为类似的字符“字符串”列表,每个字符串都有一个共同的前缀。
所以我开始简单:
> 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"
>
啊,完美!正是我需要的。除了我需要将它做到数字向量列表:
> 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)"
好的,不,那是 NOT 我需要的东西。我需要结果看起来像这样:
[[1]]
[1] "X1" "X2" "X3" "X4" "X5" "X6"
[[2]]
[1] "X7" "X8" "X9" "X10" "X11" "X12"
我怎样才能实现这一点,而不是手动循环&一次转换列表一个向量?顺便说一句,这并不太难......
> 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"
....但我知道必须有一个更聪明的方式。
答案 0 :(得分:2)
您可以使用lapply()
,它将函数应用于列表的每个元素:
lapply(aListOfNumVects, function(y) paste0("X", y))
[[1]]
[1] "X1" "X2" "X3" "X4" "X5" "X6"
[[2]]
[1] "X7" "X8" "X9" "X10" "X11" "X12"