Home > Software design >  give a value to rows in dataframe if match rows in another df in r
give a value to rows in dataframe if match rows in another df in r

Time:10-02

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)

CodePudding user response:

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

df$value <-  (df$age %in% df1$age)
  •  Tags:  
  • r
  • Related