【问题标题】:How can I use loop in order to get xtabs function results for all variable pairs?如何使用循环来获取所有变量对的 xtabs 函数结果?
【发布时间】:2014-09-23 17:25:27
【问题描述】:

我想获取数据框中所有变量对的 xtabs 函数结果(其中一个变量是永久的,另一个变量应该来自存储在数据框中的其余变量)。我知道该怎么做每次手动一对,但我有很多变量,我想找到一种循环它的方法。知道我该怎么做吗? 这是一个示例数据框:

dat <- read.table(text = " category birds    wolfs     snakes
                   yes        3        9         7
                   no         3        8         4
                   no         1        2         8
                   yes        1        2         3
                   yes        1        8         3
                   no         6        1         2
                   yes        6        7         1
                   no         6        1         5
                   yes        5        9         7
                   no         3        8         7
                   no         4        2         7
                   yes        1        2         3
                   yes        7        6         3
                   no         6        1         1
                   yes        6        3         9
                   no         6        1         1   ",header = TRUE)

我手动使用这行代码来获得我需要的东西:

xtabs(~category + birds, data = dat)
xtabs(~category + wolfs , data = dat)  
xtabs(~category + snakes, data = dat)

但是当我有很多变量时,这可能会非常低效。

【问题讨论】:

    标签: r loops


    【解决方案1】:

    试试:

    apply(dat[,2:4], 2, function(x) xtabs(~dat$category+x) )
    $birds
                x
    dat$category 1 3 4 5 6 7
             no  1 2 1 0 4 0
             yes 3 1 0 1 2 1
    
    $wolfs
                x
    dat$category 1 2 3 6 7 8 9
             no  4 2 0 0 0 2 0
             yes 0 2 1 1 1 1 2
    
    $snakes
                x
    dat$category 1 2 3 4 5 7 8 9
             no  2 1 0 1 1 2 1 0
             yes 1 0 4 0 0 2 0 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-27
      • 2017-06-11
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      相关资源
      最近更新 更多