[英]How to separate paste in list of vectors
Is there is a way to separate paste function in list of vectors?有没有办法在向量列表中分离粘贴功能?
An example : I would like from this : list(c(1),c(2,3),c(4))
which give一个例子:我想从这个:
list(c(1),c(2,3),c(4))
给出
[[1]]
[1] 1
[[2]]
[1] 2 3
[[3]]
[1] 4
Paste all values with "%" to get :用“%”粘贴所有值以获得:
[[1]]
[1] "1%"
[[2]]
[1] "2%" "3%"
[[3]]
[1] "4%"
You want the lapply()
function which takes a list and does the same thing to every element.您需要
lapply()
函数,它接受一个列表并对每个元素执行相同的操作。 The lapply()
function has two principle arguments. lapply()
函数有两个主要参数。 The first is a list (or a vector).第一个是列表(或向量)。 The second is a function.
第二个是函数。 You can either just specify the name of the function and then pass the function's remaining arguments after that, or you can write an anonymous function.
您可以只指定函数的名称,然后在此之后传递函数的剩余参数,也可以编写匿名函数。 I prefer the second method since it is more reliable as what you want to do gets more complicated.
我更喜欢第二种方法,因为它更可靠,因为您想要做的事情变得更加复杂。
l1 <- list(c(1),c(2,3),c(4))
# using lapply
lapply(l1, paste, "%", sep = "")
# with an anonymous function
lapply(l1, function(x) paste(x, "%", sep=""))
Both of these return your desired output.这两个都返回您想要的输出。
[[1]]
[1] "1%"
[[2]]
[1] "2%" "3%"
[[3]]
[1] "4%"
We could unlist
and apply paste
once as it is vectorized and change it to list
with relist
我们可以
unlist
和应用paste
,因为它被矢量一次,将其更改为list
与relist
relist(paste0(unlist(l1), "%"), skeleton = l1)
#[[1]]
#[1] "1%"
#[[2]]
#[1] "2%" "3%"
#[[3]]
#[1] "4%"
l1 <- list(c(1),c(2,3),c(4))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.