I am working with 2 data frames. I want to a file that outputs rows that appear in data frame 1, but do not appear in data frame 2. Here is sample data:
df1:
id visit
094-1 2
094-2 3
0813-1 11
0813-3 22
df2:
id visit
094-1 2
094-2 3
0819-2 8
This is what I want:
df3:
id visit
0819-2 8
I tried this, but it is not working. Can someone please help?
library(tidyverse)
df1 %in% df2 -> x
df2[!x,]-> df3
In dplyr, there is a function setdiff
for this:
df1 = data.frame(id=c("094-1","094-2","0813-1","0813-3"),visit=c(2,3,11,22))
df2 = data.frame(id=c("094-1","094-2","0819-2"),visit=c(2,3,8))
dplyr::setdiff(df2,df1)
id visit
1 0819-2 8
Or:
library(dplyr)
setdiff(df2,df1)
Using data.table
library(data.table)
fsetdiff(setDT(df2), setDT(df1))
# id visit
#1: 0819-2 8
base r
solution using a similar approach to the code included in your question. This solution uses the %in%
operator but reverses it when used in combination with the !
operator.
Data:
df1 <- data.frame(
id = c("094-1", "094-2", "0813-1", "0813-3"),
visit = c(2,3,11,22)
)
df2 <- data.frame(
id = c("094-1", "094-2", "0819-2"),
visit = c(2,3, 8)
)
Code:
df3 <- df2[!df2$id %in% df1$id,]
Output:
df3
#> id visit
#> 3 0819-2 8
Created on 2020-11-29 by the reprex package (v0.3.0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.