How to conditionally replace values in r data frame using if/then statement

前端 未结 2 446
青春惊慌失措
青春惊慌失措 2020-12-10 08:29

I\'d like to learn how to conditionally replace values in R data frame using if/then statements. Suppose I have a data frame like this one:

df <- data.fra         


        
相关标签:
2条回答
  • 2020-12-10 08:58

    You are using == instead of =(Assignment Operator) in if block. And I dont think there's need of else block in your example as you are not going to change values

     if(df$customer %in% c('paramount','pixar')){
      df$customer_id = 99
     }
    

    Above code will do the job for you

    0 讨论(0)
  • 2020-12-10 09:06

    You can use ifelse, like this:

    df$customer_id <- ifelse(df$customer %in% c('paramount', 'pixar'), 99, df$customer_id)
    

    The syntax is simple:

    ifelse(condition, result if TRUE, result if FALSE)
    

    This is vectorized, so you can use it on a dataframe column.

    0 讨论(0)
提交回复
热议问题