Reputation: 21
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
[[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%"
Upvotes: 0
Views: 294
Reputation: 887213
We could unlist
and apply paste
once as it is vectorized and change it to list
with 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))
Upvotes: 0
Reputation: 5747
You want the lapply()
function which takes a list and does the same thing to every element. The lapply()
function has two principle arguments. 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%"
Upvotes: 2