2015-10-17 71 views
1

问题:在Python中,我会使用字典和使用大量的地图/应用函数。但是,对于R,我使用这个简单的方法开始使用列表,并且我想知道是否有更高效/更优雅的方法来执行以下操作。更有效的方法来创建一个虚拟编码

在统计中,您使用虚拟变量来表示名义属性的级别。例如,A/B/C将变为00,01,10 .A/B/C/D将变成000,001,010,100。因此,每个项目只允许一个1。因此您需要n-1数字来表示n变量/字母。

在这里,我创建了一些数据:

data <- data.frame(
    "upper" = c(1,1,1,2,2,2,3,3,3), # var 1 
    "country" = c(1,2,3,1,2,3,1,2,3), # var 2 
    "price" = c(1,2,3,2,3,1,3,1,2) # var 3 
) 

创建(独特的属性水平的列表)键(属性)和值的列表:

lst <- list() 
for (attribute in colnames(data)) { 
    lst[[attribute]] = unique(data[[attribute]]) 
} 

创建虚拟编码,i用于只考虑n-1项目:

dummy <- list() 
for (attribute in colnames(data)) { 
    i <- 1 
    for (level in lst[[attribute]]) { 
    if (length(lst[[attribute]])!=i) { 
     dummy[[paste0(attribute, level)]] <- ifelse(
     data[[attribute]]==level, 
     1, 
     0 
    ) 
    } 
    i <- i + 1 
    } 
} 

结果:

dummy 
$upper1 
[1] 1 1 1 0 0 0 0 0 0 

$upper2 
[1] 0 0 0 1 1 1 0 0 0 

$country1 
[1] 1 0 0 1 0 0 1 0 0 

$country2 
[1] 0 1 0 0 1 0 0 1 0 

$price1 
[1] 1 0 0 0 0 1 0 1 0 

$price2 
[1] 0 1 0 1 0 0 0 0 1 
+1

在R中,你很少必须自己做虚拟编码。大多数建模功能为你做,如果你传递给他们一个因子变量。 – Roland

回答

1

我们创建使用model.matrixsplit列创建listlist,最后,串联的list元件一起(do.call(c,..)一个设计矩阵。

res <- do.call("c",lapply(data, function(x) { 
      x1 <- model.matrix(~0+factor(x)) 
       split(x1, col(x1))})) 

因为我们只需要前两个层次,我们可以在“资源”使用​​这将回收到list结束子集。

res[c(TRUE, TRUE, FALSE)] 
#$upper.1 
#[1] 1 1 1 0 0 0 0 0 0 

#$upper.2 
#[1] 0 0 0 1 1 1 0 0 0 

#$country.1 
#[1] 1 0 0 1 0 0 1 0 0 

#$country.2 
#[1] 0 1 0 0 1 0 0 1 0 

#$price.1 
#[1] 1 0 0 0 0 1 0 1 0 

#$price.2 
#[1] 0 1 0 1 0 0 0 0 1 
+0

伟大的解决方案!你能解释'model.matrix'里面的部分吗? – Xiphias

+1

@Xiphias我们使用'9 +'公式来移除拦截列 – akrun

相关问题