从表中获取字符串并在R中追加为列

从表中获取字符串并在R中追加为列,r,R,我有以下.csv文件: 我希望能够获取日期和代理名称(粘贴其组成部分),并将它们作为列附加到表的右侧,直到它找到不同的名称和日期,对其余的名称和日期项执行相同的操作,以获得以下结果: 对于dplyr包,我能做的唯一一件事是: library(dplyr) library(stringr) report <- read.csv(file ="test15.csv", head=TRUE, sep=",") date_pattern <- "(\\d+/\\d+/\\d+)"

我有以下.csv文件:

我希望能够获取日期和代理名称(粘贴其组成部分),并将它们作为列附加到表的右侧,直到它找到不同的名称和日期,对其余的名称和日期项执行相同的操作,以获得以下结果:

对于dplyr包,我能做的唯一一件事是:

library(dplyr)
library(stringr)


report <- read.csv(file ="test15.csv", head=TRUE, sep=",")

date_pattern <- "(\\d+/\\d+/\\d+)"
date <- str_extract(report[,2], date_pattern)

report <- mutate(report, date = date)
库(dplyr)
图书馆(stringr)

报告这可能很粗糙,但我认为它说明了几件事:a)设置
stringsAsFactors=F
;b) “预分配”数据框中的列;c)使用列名而不是列号来设置值

report<-read.csv('test15.csv', header=T, stringsAsFactors=F)

# first, allocate the two additional columns (with NAs)
report$date <- rep(NA, nrow(report))
report$agent <- rep(NA, nrow(report))

# step through the rows
for (i in 1:nrow(report)) {
  # grab current name and date if "Agent:"
  if (report[i,1] == 'Agent:') {
    currDate <- report[i+1,2]
    currName=paste(report[i,2:5], collapse=' ')
  # otherwise append the name/date
  } else {
    report[i,'date'] <- currDate
    report[i,'agent'] <- currName
  }
}
write.csv(report, 'test15a.csv')

report这正是我需要的,谢谢你的插图,爱德华!