Generate a dummy-variable

前端 未结 17 1098
遇见更好的自我
遇见更好的自我 2020-11-21 11:41

I have trouble generating the following dummy-variables in R:

I\'m analyzing yearly time series data (time period 1948-2009). I have two questions:

  1. <
17条回答
  •  星月不相逢
    2020-11-21 12:06

    I read this on the kaggle forum:

    #Generate example dataframe with character column
    example <- as.data.frame(c("A", "A", "B", "F", "C", "G", "C", "D", "E", "F"))
    names(example) <- "strcol"
    
    #For every unique value in the string column, create a new 1/0 column
    #This is what Factors do "under-the-hood" automatically when passed to function requiring numeric data
    for(level in unique(example$strcol)){
      example[paste("dummy", level, sep = "_")] <- ifelse(example$strcol == level, 1, 0)
    }
    

提交回复
热议问题