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

标签 r multiple-columns strsplit

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

我的数据是这样的:

> 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 个信息( authorsyeartitle )分成三个不同的列,这样它就是:
> 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/

相关文章:

html - Bootstrap 4,根据我们在第一列上滚动的位置更改第二列内容

shell - 基于linux中的两个键合并两个长度不等的文件

R - 数据框中两组之间的差异

r - 如何在 R 中将 str_split 与正则表达式一起使用?

r - 将不同列表的子列表组合成数据框列表

r - ggplot2 热图,带条件的色标

JAVA:在多列上对 ArrayList<ArrayList<Integer>> 进行排序

按行 reshape 矩阵

r - 仅在 1 列中将数字更改为单词

r - 在 R 中拆分不分隔的字符串和数值变量