r-从现有数据帧或数据表创建多个虚拟对象



我正在寻找下面发布的解决方案的快速扩展。在其中,Frank展示了一个示例数据表

test <- data.table("index"=rep(letters[1:10],100),"var1"=rnorm(1000,0,1))

您可以使用以下代码快速制作假人

inds <- unique(test$index) ; test[,(inds):=lapply(inds,function(x)index==x)]

现在,我想将此解决方案扩展到具有多行索引的data.table,例如

new <- data.table("id" = rep(c("Jan","James","Dirk","Harry","Cindy","Leslie","John","Frank"),125), "index1"=rep(letters[1:5],200),"index2" = rep(letters[6:15],100),"index3" = rep(letters[16:19],250))

我需要为许多假人做这件事,理想情况下,解决方案会让我得到4件事:

  1. 每个索引的总计数
  2. 每个索引出现的平均次数
  3. 每个id的每个索引的计数
  4. 每个id的每个索引的平均值

在我的实际案例中,索引的命名不同,因此解决方案需要能够循环使用我认为的列名。

感谢

Simon

如果您只需要该列表中的四个项目,您应该将其制成表格:

indcols <- paste0('index',1:3)
lapply(new[,indcols,with=FALSE],table) # counts
lapply(new[,indcols,with=FALSE],function(x)prop.table(table(x))) # means
# or...
lapply(
  new[,indcols,with=FALSE],
  function(x){
    z<-table(x)
    rbind(count=z,mean=prop.table(z))
  })

这提供

$index1
          a     b     c     d     e
count 200.0 200.0 200.0 200.0 200.0
mean    0.2   0.2   0.2   0.2   0.2
$index2
          f     g     h     i     j     k     l     m     n     o
count 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0
mean    0.1   0.1   0.1   0.1   0.1   0.1   0.1   0.1   0.1   0.1
$index3
           p      q      r      s
count 250.00 250.00 250.00 250.00
mean    0.25   0.25   0.25   0.25


以前的方法适用于data.frame或data.table,但相当复杂。对于data.table,可以使用melt语法:

melt(new, id="id")[,.(
  N=.N, 
  mean=.N/nrow(new)
), by=.(variable,value)]

它给出

    variable value   N mean
 1:   index1     a 200 0.20
 2:   index1     b 200 0.20
 3:   index1     c 200 0.20
 4:   index1     d 200 0.20
 5:   index1     e 200 0.20
 6:   index2     f 100 0.10
 7:   index2     g 100 0.10
 8:   index2     h 100 0.10
 9:   index2     i 100 0.10
10:   index2     j 100 0.10
11:   index2     k 100 0.10
12:   index2     l 100 0.10
13:   index2     m 100 0.10
14:   index2     n 100 0.10
15:   index2     o 100 0.10
16:   index3     p 250 0.25
17:   index3     q 250 0.25
18:   index3     r 250 0.25
19:   index3     s 250 0.25

@Arun在一条评论中提到了这种方法(我想他也实现了…?)。要了解它的工作原理,首先看一下melt(new, id="id"),它转换了原始数据。表。

如注释中所述,熔化data.table需要为某些版本的data.table包安装和加载reshape2



如果你也需要假人,它们可以像链接的问题中那样循环制作:

newcols <- list()
for (i in indcols){
    vals = unique(new[[i]])
    newcols[[i]] = paste(vals,i,sep='_')
    new[,(newcols[[i]]):=lapply(vals,function(x)get(i)==x)]
}

为了方便起见,这将与每个变量相关联的列组存储在newcols中。如果你只想用这些假人(而不是上面解决方案中的基本变量)来做表格,你可以做

lapply(
  indcols,
  function(i) new[,lapply(.SD,function(x){
    z <- sum(x)
    list(z,z/.N)
  }),.SDcols=newcols[[i]] ])

这给出了类似的结果。我只是用这种方式来说明如何使用data.table语法。您可以再次避免方括号和此处的.SD

lapply(
  indcols,
  function(i) sapply(
    new[, newcols[[i]], with=FALSE],
    function(x){
      z<-sum(x)
      rbind(z,z/length(x))
    }))

但是不管怎样:如果你能抓住底层变量,就使用table

最新更新