Generate a dummy-variable

前端 未结 17 1058
遇见更好的自我
遇见更好的自我 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:10

    I use such a function (for data.table):

    # Ta funkcja dla obiektu data.table i zmiennej var.name typu factor tworzy dummy variables o nazwach "var.name: (level1)"
    factorToDummy <- function(dtable, var.name){
      stopifnot(is.data.table(dtable))
      stopifnot(var.name %in% names(dtable))
      stopifnot(is.factor(dtable[, get(var.name)]))
    
      dtable[, paste0(var.name,": ",levels(get(var.name)))] -> new.names
      dtable[, (new.names) := transpose(lapply(get(var.name), FUN = function(x){x == levels(get(var.name))})) ]
    
      cat(paste("\nDodano zmienne dummy: ", paste0(new.names, collapse = ", ")))
    }
    

    Usage:

    data <- data.table(data)
    data[, x:= droplevels(x)]
    factorToDummy(data, "x")
    

提交回复
热议问题