我试图在数据框中将字符向量拆分为三个不同的向量。
我的数据是这样的:
> df <- data.frame(filename = c("Author1 (2010) Title of paper",
"Author2 et al (2009) Title of paper",
"Author3 & Author4 (2004) Title of paper"),
stringsAsFactors = FALSE)
我想将这 3 个信息(
authors
、 year
、 title
)分成三个不同的列,这样它就是:> df
filename author year title
1 Author1 (2010) Title1 Author1 2010 Title1
2 Author2 et al (2009) Title2 Author2 et al 2009 Title2
3 Author3 & Author4 (2004) Title3 Author3 & Author4 2004 Title3
我用过
strsplit
拆分每个 filename
在 3 个元素的向量中: df$temp <- strsplit(df$filename, " \\(|\\) ")
但是现在,我找不到将每个元素放在单独的列中的方法。我可以访问这样的特定信息:
> df$temp[[2]][1]
[1] "Author2 et al"
但找不到如何将其放在其他列中
> df$author <- df$temp[[]][1]
Error
最佳答案
你可以试试 tstrsplit
来自 data.table
的开发版
library(data.table)#v1.9.5+
setDT(df)[, c('author', 'year', 'title') :=tstrsplit(filename, ' \\(|\\) ')]
df
# filename author year
#1: Author1 (2010) Title of paper Author1 2010
#2: Author2 et al (2009) Title of paper Author2 et al 2009
#3: Author3 & Author4 (2004) Title of paper Author3 & Author4 2004
# title
#1: Title of paper
#2: Title of paper
#3: Title of paper
编辑:包括 OP 的拆分模式以删除空格。
关于r - 将strsplit的结果分配给数据框的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31357963/