【问题标题】:matching dataset with data in csv file in R将数据集与R中的csv文件中的数据匹配
【发布时间】:2018-08-09 14:56:04
【问题描述】:

假设我有数据

mydat=structure(list(id = 1:6, x2 = c(12L, 12L, 12L, 12L, 12L, 12L), 
    x3 = c(12L, 12L, 12L, 12L, 12L, 12L)), .Names = c("id", "x2", 
"x3"), class = "data.frame", row.names = c(NA, -6L))

我也有文件 csv

test=read.csv(path,sep=";", dec",")

它有这个结构

test=structure(list(id = 1:5, x2 = c(12L, 12L, 12L, 12L, 12L), x3 = c(12L, 
12L, 12L, 12L, 12L)), .Names = c("id", "x2", "x3"), class = "data.frame", row.names = c(NA, 
-5L))

我怎样才能匹配这两个数据集,从mydat 被删除 与test具有相似ID的观察?

I.E.输出必须是

id  x2  x3
6   12  12

因为mydat 中的id 1,2,3,4,5test 数据集相似。

【问题讨论】:

  • 或者如果你不是 tidyverse 的粉丝,你可以使用 merge(..., all=T) 然后删除合并成功的行。
  • @DanY 你到底是如何删除行的?那是OP问题
  • 这里有一个更好的评论:mydat[!(mydat$id %in% test$id), ] 谢谢你让我诚实:)

标签: r dataframe dplyr data.table


【解决方案1】:

你可以使用来自 dplyr 的anti_join`

 dplyr::anti_join(mydat,test)
Joining, by = c("id", "x2", "x3")
  id x2 x3
1  6 12 12

在基础 R 中:您可以将数据折叠成字符串并进行比较:

mydat[!do.call(paste,mydat)%in%do.call(paste,test),]
  id x2 x3
6  6 12 12

【讨论】:

    【解决方案2】:

    使用 R 基础。

    > mydat[setdiff(mydat$id, test$id), ]
      id x2 x3
    6  6 12 12
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2018-08-24
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      相关资源
      最近更新 更多