在 R 中选择性地读取 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 L.P.   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 L.P.,389546
2,1,19940210,19950912,Schueman Transfer, Inc.,1164239
2,1,19940217,19950912,Spacelabs Medical, Inc.,1164336

问题在于,某些Applicant名称包含逗号,因此它们被读取时就好像它们属于不同的列,而实际上它们不属于。

有没有一种简单的方法a) "教导"R 将字符串变量保持在一起,而不管两者之间的逗号b) 阅读前 4 列,然后为最后一个逗号后面的所有内容添加额外的列?

考虑到数据的长度,我无法在 excel 中完全打开它,否则这将是一个简单的选择。

如果您的示例编写在"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 L.P.  389546
# 5        2        1 19940210   19950912 Schueman Transfer Inc. 1164239
# 6        2        1 19940217   19950912 Spacelabs Medical Inc. 1164336

这提供了一个非常愚蠢的解决方法,但它为我提供了诀窍(因为我并不真正关心申请人名称 atm。但是,我希望有更好的解决方案。

步骤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)

这是一个愚蠢的补丁,但它在这种特定情况下可以解决问题

最新更新