sarovasta
sarovasta

Reputation: 89

If a value exists in data.frame then... (R)

I have two data.frame:

A <- c("name", "city", "code")
B <- c("code", "city")

I would like to see whether each value of A$city exists in B$city and in that case to report the correspondent B$code value in a new column of A. Here is what I've done:

A$code <- ""
found <- is.element(A$city, B$city)

Then, how should I perform the if statement?

Upvotes: 0

Views: 1591

Answers (1)

ardaar
ardaar

Reputation: 1274

You're looking for the %in% operator. Here's a reprex:

library('tidyverse')

A <- tribble(
  ~name, ~city, ~code,
  'foo', 'newark', '',
  'bar', 'philly', '',
  'fighter', 'sf', ''
)

B <- tribble(
  ~code, ~city,
  'X', 'philly',
  'Y', 'newark'
)

A = A %>%
  mutate(code = ifelse(city %in% B$city, B$code, NA))

A

#> # A tibble: 3 x 3
#>      name   city  code
#>     <chr>  <chr> <chr>
#> 1     foo newark     X
#> 2     bar philly     Y
#> 3 fighter     sf  <NA>

Let me know if I'm missing something. You can replace the NA in the ifelse function with "" or whatever.

Upvotes: 1

Related Questions