vendredi 6 août 2021

R: looping through a list and adding values to the data frame

I am still new to R and I was not able to find a solution to my problem online.

I would like to create a loop that goes though the list of variables and add a value ("1" or "0") to a new column in my data frame based on the if statement. If the variable in my list (db) is identical to the variable in col_1 print "1" in col_2, else print "0".

I tried it by:

col1 <- c('aa','c','b','ab','ac','ad')
df <- data.frame(col1)
df$col2 <-NA 

db <- c('aa', 'ab', 'ac', 'ad')

for(i in db) {  
  if(df$col1 == i){
    df$col2 == 1
  } else{
    df$col2 == 0
  }
}

Aucun commentaire:

Enregistrer un commentaire