在R中有select地读取txt文件

我正在寻找一个简单的修复方法来读取在Excel中打开时看起来像这样的txt文件:

IDmaster By_uspto App_date Grant_date Applicant Cited 2 1 19671106 19700707 Motorola Inc 1052446 2 1 19740909 19751028 Gen Motors Corp 1062884 2 1 19800331 19820817 Amp Incorporated 1082369 2 1 19910515 19940719 Dell Usa LP 389546 2 1 19940210 19950912 Schueman Transfer Inc. 1164239 2 1 19940217 19950912 Spacelabs Medical Inc. 1164336 

编辑:打开记事本中的txt文件看起来像这样(用逗号)。 最后两行显示了这个问题。

 IDmaster,By_uspto,App_date,Grant_date,Applicant,Cited 2,1,19671106,19700707,Motorola Inc,1052446 2,1,19740909,19751028,Gen Motors Corp,1062884 2,1,19800331,19820817,Amp Incorporated,1082369 2,1,19910515,19940719,Dell Usa LP,389546 2,1,19940210,19950912,Schueman Transfer, Inc.,1164239 2,1,19940217,19950912,Spacelabs Medical, Inc.,1164336 

问题是一些Applicant名字包含逗号,所以他们被认为是属于不同的列,他们实际上没有。

是否有一个简单的方法来“教”R保持stringvariables在一起,无论之间逗号b)读取前4列,然后在最后一个逗号后面添加一个额外的列?

鉴于数据的长度,我不能完全在Excel中打开它,否则这将是一个简单的select。

如果您的示例是在“Test.csv”文件中编写的,请尝试:

 read.csv(text=gsub(', ', ' ', paste0(readLines("Test.csv"),collapse="\n")), quote="'", stringsAsFactors=FALSE) 

它返回:

 # IDmaster By_uspto App_date Grant_date Applicant Cited # 1 2 1 19671106 19700707 Motorola Inc 1052446 # 2 2 1 19740909 19751028 Gen Motors Corp 1062884 # 3 2 1 19800331 19820817 Amp Incorporated 1082369 # 4 2 1 19910515 19940719 Dell Usa LP 389546 # 5 2 1 19940210 19950912 Schueman Transfer Inc. 1164239 # 6 2 1 19940217 19950912 Spacelabs Medical Inc. 1164336 

这提供了一个非常愚蠢的解决方法,但它对我来说是诀窍(因为我真的不在乎申请人的名字atm。但是,我希望有一个更好的解决scheme。

步骤1:在记事本中打开.txt文件,添加五个列名V1,V2,V3,V4,V5(确保用多个逗号分隔)。

 bc <- read.table("data.txt", header = T, na.strings = T, fill = T, sep = ",", stringsAsFactors = F) library(data.table) sapply(bc, class) unique(bc$V5) # only NA so can be deleted setDT(bc) bc <- bc[,1:10, with = F] bc$Cited <- as.numeric(bc$Cited) bc$Cited[is.na(bc$Cited)] <- 0 bc$V1 <- as.numeric(bc$V1) bc$V2 <- as.numeric(bc$V2) bc$V3 <- as.numeric(bc$V3) bc$V4 <- as.numeric(bc$V4) bc$V1[is.na(bc$V1)] <- 0 bc$V2[is.na(bc$V2)] <- 0 bc$V3[is.na(bc$V3)] <- 0 bc$V4[is.na(bc$V4)] <- 0 head(bc, 10) bc$Cited <- with(bc, Cited + V1 + V2 + V3 + V4) 

这是一个愚蠢的补丁,但它在这个特定的上下文中伎俩