2

有一个 data.frame 附加到现有文件。当它被 write.table 函数附加时,它可能会导致重复记录到文件中。这是示例代码:

df1<-data.frame(name=c('a','b','c'), a=c(1,2,2))
write.csv(df1, "export.csv", row.names=FALSE, na="NA"); 

#"export.csv" keeps two copies of df1
write.table(df1,"export.csv", row.names=F,na="NA",append=T, quote= FALSE, sep=",", col.names=F);

所以理想情况下,输出文件应该只保留一份df1。但是 write.table 函数没有任何用于重复检查的参数。

感谢您提前提出任何建议。

4

2 回答 2

8

您可以从文件中读取 data.frame,rbind使用新的 data.frame 并检查重复值。为了编写效率,仅附加非重复行。

如果您提出这个问题是因为您正在使用大数据集并且关注读/写时间,请查看data.tablefread包。

# initial data.frame
df1<-data.frame(name=c('a','b','c'), a=c(1,2,2))
write.csv(df1, "export.csv", row.names=FALSE, na="NA")

# a new data.frame with a couple of duplicate rows
df2<-data.frame(name=c('a','b','c'), a=c(1,2,3))
dfRead<-read.csv("export.csv") # read the file
all<-rbind(dfRead, df2) # rbind both data.frames
# get only the non duplicate rows from the new data.frame
nonDuplicate <- all[!duplicated(all)&c(rep(FALSE, dim(dfRead)[1]), rep(TRUE, dim(df2)[1])), ]
# append the file with the non duplicate rows
write.table(nonDuplicate,"export.csv", row.names=F,na="NA",append=T, quote= FALSE, sep=",", col.names=F)
于 2015-01-15T19:01:09.360 回答
1
> # Original Setup ----------------------------------------------------------
> df1 <- data.frame(name = c('a','b','c'), a = c(1,2,2))
> write.csv(df1, "export.csv", row.names=FALSE, na="NA"); 
> 
> # Add Some Data -----------------------------------------------------------
> df1[,1]  <- as.character(df1[,1])
> df1[,2]  <- as.numeric(df1[,2])
> df1[4,1] <- 'd'
> df1[4,2] <- 3
> 
> # Have a Look at It -------------------------------------------------------
> head(df1)
  name a
1    a 1
2    b 2
3    c 2
4    d 3
> 
> # Write It Out Without Duplication ----------------------------------------
> write.table(df1, "export.csv", row.names=F, na="NA", 
+             append = F, quote= FALSE, sep = ",", col.names = T)
> 
> # Proof It Works ----------------------------------------------------------
> proof <- read.csv("export.csv")
> head(proof)
  name a
1    a 1
2    b 2
3    c 2
4    d 3

您也可以按照建议rbind或简单地使用write.csvor write.tablewith andappend = T选项的问题评论进行操作,确保正确处理行名和列名。

但是,我也建议使用 andreadRDSsaveRDSand 只是覆盖rds对象而不是追加作为最佳实践。RDSHadley 和 R 中的其他顶级名称推荐使用。

于 2015-01-15T18:51:07.950 回答