如何将列表类变量更改为r中的字符串

时间:2018-05-12 22:35:21

标签: r

我是R的新手,我非常有兴趣学习这个精彩的数据分析程序。

我正在制作一份由我的老师提供的关于推文数据的工作表。我发现一项任务非常困难,因为我需要按订单准备数据,所以我可以将其传递给下一个问题。我想问一下如何将“list”类变量更改为“string”类。以下是变量的前6个元素:

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)

我想把它们改成像:

[[1]]
 NA or 0

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

1 个答案:

答案 0 :(得分:0)

执行:

library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
x <- round(x*100)
write.zoo(head(x), sep = ",")
# "Index","Open","High","Low","Close"
# 2007-01-02,5004,5012,4995,5012
# 2007-01-03,5023,5042,5023,5040
# 2007-01-04,5042,5042,5026,5033
# 2007-01-05,5037,5037,5022,5033
# 2007-01-06,5024,5024,5011,5018
# 2007-01-07,5013,5022,4999,4999

但如果您允许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 成为&#34;&#34;,则更容易:

character(0)

甚至更短:

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