【问题标题】:Recovering tapply results into the original data-frame in R将 tapply 结果恢复到 R 中的原始数据帧中
【发布时间】:2012-02-13 20:04:54
【问题描述】:

我有一个数据框,其中包含公司在不同年份向不同国家/地区的年度出口。我的问题是我需要创建一个变量,表示每年每个国家有多少家公司。我可以用“tapply”命令完美地做到这一点,比如

incumbents <- tapply(id, destination-year, function(x) length(unique(x)))

它工作得很好。我的问题是现任者的长度为length(destination-year),我需要它的长度为length(id)——每年都有很多公司为每个目的地提供服务——以便在随后的回归中使用它(当然,以与年份和目的地)。 “for”循环可以做到这一点,但由于数据库有点庞大,因此非常耗时。

有什么建议吗?

【问题讨论】:

  • 抱歉没有示例数据...新手错误

标签: r dataframe tapply


【解决方案1】:

您没有提供可重现的示例,因此我无法对此进行测试,但您应该可以使用ave

incumbents <- ave(id, destination-year, FUN=function(x) length(unique(x)))

【讨论】:

    【解决方案2】:

    只需将tapply 摘要与merge 的原始数据框“合并”即可。

    由于您没有提供示例数据,我做了一些。相应修改。

    n           = 1000
    id          = sample(1:10, n, replace=T)
    year        = sample(2000:2011, n, replace=T)
    destination = sample(LETTERS[1:6], n, replace=T)
    
    `destination-year` = paste(destination, year, sep='-')
    
    dat = data.frame(id, year, destination, `destination-year`)
    

    现在将您的摘要制成表格。请注意我是如何重新格式化为数据框并使名称与原始数据匹配的。

    incumbents = tapply(id, `destination-year`, function(x) length(unique(x)))
    incumbents = data.frame(`destination-year`=names(incumbents), incumbents)
    

    最后,与原始数据重新合并:

    merge(dat, incumbents)
    

    顺便说一句,tapply 可以直接将这两个变量作为列表处理,而不是像您已经完成的那样将 destinationyear 组合成第三个变量:

    incumbents = melt(tapply(id, list(destination=destination, year=year), function(x) length(unique(x))))
    

    【讨论】:

      【解决方案3】:

      使用@JohnColby 的优秀示例数据,我想到了更多类似的东西:

      #I prefer not to deal with the pesky '-' in a variable name
      destinationYear = paste(destination, year, sep='-')
      
      dat = data.frame(id, year, destination, destinationYear)
      
      #require(plyr)
      dat <- ddply(dat,.(destinationYear),transform,newCol = length(unique(id)))
      
      #Or if more speed is required, use data.table
      require(data.table)
      datTable <- data.table(dat)
      
      datTable <- datTable[,transform(.SD,newCol = length(unique(id))),by = destinationYear]
      

      【讨论】:

        猜你喜欢
        • 2018-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 1970-01-01
        • 2014-02-17
        • 2017-05-04
        • 1970-01-01
        相关资源
        最近更新 更多