T X
T X

Reputation: 613

How to delete specific record of one dataframe according to values in another dataframe in R

I have two dataframe (dat1 & dat2). Some records in dat2 need to be deleted, according to if var1 in dat1 is negative. I use the following codes, but I think they are not the best one, because I use an extra temporary dataframe tmp. Could we have a better method?

library(dplyr)

Date1 <- c("1999-12-17", "2005-1-5", "2003-11-2", "2005-6-12", "2005-8-9")
Date1 <- as.POSIXct(Date1, tz = "UTC")

Date2 <- c("2005-1-5", "2005-6-12", "2005-8-9")
Date2 <- as.POSIXct(Date2, tz = "UTC")

var1 <- c(-3, -10, 9, 5, 8)
var2 <- c(0.2, 0.6, 0.15)

dat1 <- data.frame(Date1, var1)
dat2 <- data.frame(Date2, var2)

#Below is what I did
tmp <- inner_join(dat1, dat2, by = c("Date1" = "Date2"))
tmp <- tmp[-tmp$var1 < 0, ]

dat2 <- tmp[, c(1,3)] 

Upvotes: 0

Views: 39

Answers (2)

Emily Kothe
Emily Kothe

Reputation: 872

Given you're already using dplyr, why not make better use of pipes, filter, and select as such

library(dplyr)
dat2 %>%
  left_join(dat1, by = c("Date2" = "Date1")) %>%
  filter(var1 >= 0) %>% 
  select(-var1)

Upvotes: 1

Sonny
Sonny

Reputation: 3183

Something like this should work:

dat2 %>%
  left_join(dat1, by = c("Date2" = "Date1")) %>%
  filter(var1 > 0) %>%
  mutate(var1 = NULL)

Upvotes: 2

Related Questions