Difference between if() and ifelse() functions

后端 未结 3 1725
鱼传尺愫
鱼传尺愫 2020-11-29 11:50

I want to dummy code i.e. create flag variables for column Species.

I wrote the below code:

create_dummies <- function(data, categorical_preds){
          


        
3条回答
  •  盖世英雄少女心
    2020-11-29 12:21

    The warning message:

      the condition has length > 1 and only the first element will be used
    

    tells you that using a vector in if condition is equivalent to use its first element :

    [if (v == 1)] ~ [if (v[1] == 1)] ## v here is a vector
    

    You should use the vectorized ifelse. For example you can write your condition like this:

    create_dummies<-function(data, categorical_preds){
      ## here I show only the first condition 
      data$setosa_flg <-
           ifelse (categorical_preds=="setosa",1,0)
      data
    }
    

提交回复
热议问题