1

I have two df:

df <- data.frame("name" = c("CARL", "JACK", "TOM", "JOHN", "TIM", 
    "SAM"), "age" = c("3", "2", "1", "5", "9", "8"))

df1 <- data.frame("name" = c("BILLI", "JIMMI", "JANE"), "age" = c("3", 
    "0", "9"))

df
name      age
1 CARL     3
2 JACK     2
3  TOM     1
4 JOHN     5
5  TIM     9
6  SAM     8

df1
   name    age
1 BILLI     3
2 JIMMI     0
3  JANE     9

I would like to create a new column in df where a value of 1 is given if the rows of the AGE column are equal to the rows of the AGE column of df1, otherwise give a value of 0. Example

 df
    name     age  value
    1 CARL     3   1
    2 JACK     2   0
    3  TOM     1   0
    4 JOHN     5   0
    5  TIM     9   1
    6  SAM     8   0

that doesnt work:

df$value <- NULL
df$value <- ifelse(df[df$age== df1$age),], 1,0)
jonny jeep
  • 383
  • 3
  • 12
  • 1
    Try `transform(df, value=as.numeric(df$age == df1$age))`. – jay.sf Oct 01 '22 at 13:59
  • 1
    Please do a [`dput()`](https://stackoverflow.com/questions/49994249/example-of-using-dput) of your data and include it in your question. – Kitswas Oct 01 '22 at 13:59

1 Answers1

3

As these have different number of rows, use %in% instead of ==

df$value <- +(df$age %in% df1$age)
akrun
  • 874,273
  • 37
  • 540
  • 662