Difference between if() and ifelse() functions

后端 未结 3 1682
鱼传尺愫
鱼传尺愫 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:16

    If else should be used when you build function, to run certain parts of function given when given codition is true (one condition, length==1) . ifelse you should use in transforming your data.frame.

    Help on if else:

    cond A length-one logical vector that is not NA. Conditions of length greater than one are accepted with a warning, but only the first element is used. Other types are coerced to logical if possible, ignoring any class.

    For this purpose (if vector is factor) you can use model.matrix to create dummy variables.

    mat<-model.matrix(~iris$Species-1)
    mat<-as.data.frame(mat)
    names(mat)<-unique(iris$Species)
    
    > str(mat)
    'data.frame':   150 obs. of  3 variables:
     $ setosa    : num  1 1 1 1 1 1 1 1 1 1 ...
     $ versicolor: num  0 0 0 0 0 0 0 0 0 0 ...
     $ virginica : num  0 0 0 0 0 0 0 0 0 0 ...
    

提交回复
热议问题