假设代码是一致的 - 例如,编码的行都10
以相同的方式格式化,您可以执行以下操作:
text <- "10,abc,20141001,test@test.com,555-555-5555
20,abc,20141001,123 Main St,Springfield,CT,10001
10,xyz,20141001,test2@test.com,111-111-1111"
library(data.table)
conn <- textConnection(text)
result.10 <- do.call(rbind,lapply(1:3,function(i){
x=readLines(conn,n=1)
if(grepl("^10,",x)) return(setNames(strsplit(x,",")[[1]],c("code","name","date","email","phone")))
# if(grepl("^20,",x)) return(setNames(strsplit(x,",")[[1]],c("code","name","date","address","city","state","zipcode")))
}))
result.10 <- as.data.table(result.10)
result.10[,code:=NULL]
result.10
# name date email phone
# 1: abc 20141001 test@test.com 555-555-5555
# 2: xyz 20141001 test2@test.com 111-111-1111
然后对 等做同样的事情result.20
。然后你必须将文件合并为一个,可能基于名称(也许是日期??),类似于:
setkey(result.10,name,date)
setkey(result.20,name,date)
result <- merge(result.10,result.20,all.x=TRUE,all.y=TRUE)
result
# name date email phone address city state zipcode
# 1: abc 20141001 test@test.com 555-555-5555 123 Main St Springfield CT 10001
# 2: xyz 20141001 test2@test.com 111-111-1111 NA NA NA NA
我使用的是 data.tables 而不是数据框,因为对于这么大的文件,它可能会更快。