How to Paste List of Items in R

R paste values of list for every entry in the Data Frame

Base R using sapply :

politicans_v2$mentions_chr <- sapply(politicans_v2$mentions, paste0, collapse = ' ')

how to create a list with the names generated by paste function?

Use setNames like this:

setNames(list(1:4), paste("rer","erer"))
## $`rer erer`
## [1] 1 2 3 4

or

`names<-`(list(1:4), paste("rer","erer"))
## $`rer erer`
## [1] 1 2 3 4

or

L <- list(1:4)
names(L) <- paste("rer","erer")
L
## $`rer erer`
## [1] 1 2 3 4

R Paste List to Bind

We can use mget on the pasted strings to return the values of the object names in a list and then rbind the elements with do.call

`row.names<-`(do.call(rbind, mget(paste0('data', 1:4))), NULL)

Or use pattern in ls

do.call(rbind, mget(ls(pattern = '^data\\d+$')))

With data.table, it would be rbindlist

library(data.table)
rbindlist(mget(paste0('data', 1:4)))

Paste items in a list where some of the items contain a vector

You need to repeat the shorter vectors to be the same length as the longer vectors. One way to do this is to convert the list to a data.frame, then you can apply your paste function to each row:

myfun <- function(x) paste(names(x), "=", x, collapse="&", sep="")

apply(as.data.frame(paramlist2), 1, myfun)

Is there a way to paste together the elements of a vector in R without using a loop?

You just need to use the collapse argument:

paste(x,collapse="")

Apply paste over a list of vectors to get a list of strings

Your initial approach was almost correct, you just need to add collapse = " " in order to concatenate the vectors into one string in each element of your list

lapply(data, paste, collapse = " ") 
# $foo
# [1] "first m last"
#
# $bar
# [1] "first m last"


Related Topics



Leave a reply



Submit