【问题标题】:Replace a factor column by its counts用计数替换因子列
【发布时间】:2017-07-10 17:21:57
【问题描述】:

我一直在尝试找到一种方法来用它的计数/频率替换 R 因子。例如,以下数据框会产生类似这样的内容

t <- data.frame(color = c('red', 'blue', 'red', 'green', 'red', 'red', 'green'))

  color
1   red
2  blue
3   red
4 green
5   red
6   red
7 green

我有兴趣用它的出现次数替换因子,所以它看起来像这样

 color
1    4
2    1
3    4
4    2
5    4
6    4
7    2

因为级别 red 的计数为 4,blue 1 和 green 2。

到目前为止,我的所有尝试似乎都过于复杂(应用、合并、表格......),而且它们没有产生我需要的东西。

对我如何解决这个问题有什么建议吗?

【问题讨论】:

  • 我删除了不必要的 as.factor 行,因为它是由 data.frame 隐式完成的
  • @RichScriven 感谢编辑和格式化。

标签: r


【解决方案1】:

您可以将向量制成表格,然后使用级别的整数值对其进行扩展。

t$color <- with(t, tabulate(color)[color])
t
#   color
# 1     4
# 2     1
# 3     4
# 4     2
# 5     4
# 6     4
# 7     2

另一种选择是将ave()length() 结合使用。

with(t, ave(seq_along(color), color, FUN = length))
# [1] 4 1 4 2 4 4 2

【讨论】:

    【解决方案2】:
    x <- read.table(text="  color
                    1   red
                    2  blue
                    3   red
                    4 green
                    5   red
                    6   red
                    7 green", header=TRUE)
    
    data.frame(x, count=sapply(1:nrow(x), function(i) sum(x$color==x$color[i])))
    # color count
    # 1   red     4
    # 2  blue     1
    # 3   red     4
    # 4 green     2
    # 5   red     4
    # 6   red     4
    # 7 green     2
    

    【讨论】:

      【解决方案3】:

      使用data.table

      setDT(t)
      t[, color2 := .N, by = color][, .(color = color2)]
      
         color
      1:     4
      2:     1
      3:     4
      4:     2
      5:     4
      6:     4
      7:     2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-31
        • 1970-01-01
        • 2016-09-30
        • 1970-01-01
        • 2017-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多