我试图将一个具有这种格式的数据的文件解析为R:
Author: Books:
Jane Austen Sense and Sensibility
Justin Bieber NA
Shakespeare The Taming of the Shrew | Much Ado About Nothing它有一对多的结构。我想得到的是这样一个长格式的数据框架:
Author: Books:
Jane Austen Sense and Sensibility
Shakespeare The Taming of the Shrew
Shakespeare Much Ado About Nothing如果你想把所有的书都交给一个作者,或者找出谁写了一本特定的书,这就更方便了。
更普遍地说,如何将(字符串,值列表)格式中的数据帧转换为(string1,value1);(string1,value2);(string2,value3)格式?我知道如何使用str拆分,但我对这里的数据帧操作不太确定。
优点:我想要一些快速工作的东西(我在现实生活中有一个很大的数据集)。
我正在考虑构建一个大小合适的空数据框架(这是由sum(sapply(df$colWithListOfStrings,length)))提供的),并使用一个for循环来填充它。
PS:我们在这里假设一本书只有一个作者。
发布于 2015-04-02 10:19:45
您可以从cSplit包中使用splitstackshape (来自Ananda Mahto的非常好的工具)
library(splitstackshape)
cSplit(data, splitCols=2, sep = "|", direction = "long")[!is.na(Books)]
# Author Books
#1: Jane Austen Sense and Sensibility
#2: Shakespeare The Taming of the Shrew
#3: Shakespeare Much Ado About Nothingdput(数据)
structure(list(Author = c("Jane Austen", " Justin Bieber",
" Shakespeare"), Books = c(" Sense and Sensibility ",
" NA", " The Taming of the Shrew | Much Ado About Nothing"
)), .Names = c("Author", "Books"), class = "data.frame", row.names = c(NA,
-3L))https://stackoverflow.com/questions/29410028
复制相似问题