将 strsplit 的结果分配给数据框的多列

2024-03-26

我正在尝试将数据框中的字符向量拆分为三个不同的向量。

我的数据是这样的:

> 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 的分割模式以删除空格。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 strsplit 的结果分配给数据框的多列 的相关文章

随机推荐