简体   繁体   中英

how change a list class variable into string in r

I am very new to R and I am so interested in learning this wonderful program for data analysis.

I was working on a worksheet which was given by my teacher on tweets data. I found one task so difficult and I could get passed into the next question as I need the data ready by order. I would like to ask how to change a "list" class variable into "string" class. The following is the first 6 elements of the variable:

head(tweets.merged$hashtag_and_mentioned, 6)
[[1]]
character(0)

[[2]]
[1] "#Aufbruch."      " @MartinSchulz:" " #Deutschland"  

[[3]]
[1] "#zeitfuermartin" " @MartinSchulz."

[[4]]
[1] "#zeitfuermartin" " @MartinSchulz" 

[[5]]
character(0)

[[6]]
character(0)

I want to change them into some thing like:

[[1]]
 NA or 0

[[2]]
[1] "Aufbruch. @MartinSchulz: #Deutschland"  

Do:

l <- tweets.merged$hashtag_and_mentioned
unlist(lapply(l, function(x) if (length(x) == 0) {NA} else {paste(x, collapse = "")})) # or change NA to 0

But if you allow character(0) to become "", it is even easier:

unlist(lapply(l, function(el) paste(el, collapse = ""))

Or even shorter:

unlist(lapply(l, paste, collapse = ""))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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