【问题标题】:how to divide my dataset by the number of times a value appears in R如何将我的数据集除以值出现在 R 中的次数
【发布时间】:2015-10-13 16:56:01
【问题描述】:

我有一个数据集,需要知道数字 1、数字 0 和数字 -1 平均出现的次数。但这不是传统的平均值。我解释一下:

这是我的数据集的一部分:

position
 1
 1
 1
 0
 0
-1
 0
-1
-1
-1
-1
-1
 1
 1

因此,如果我将每个数字按向量出现的次数作为子集,我将拥有:

position '1'   position '-1'  position '0'
  X1  X2         X1  X2         X1  X2
  1   1          -1  -1          0   0
  1   1              -1          0
  1                  -1
                     -1
                     -1

这样我可以找到 1 的平均值:(X1+X2)/2 其中 2 是出现的向量的数量。这取决于并且可以是由数字连续出现的次数给出的任何数字。

这有点令人困惑,但我希望你能理解我的意思。我一直在想如何做到这一点,但找不到办法。

非常感谢!

【问题讨论】:

  • 函数rle会让你非常接近你想要的,你只需要稍微重新排列它的输出。

标签: r


【解决方案1】:

@KonradRudolph 提到,rle 是必经之路。然后你可以使用split 来获得正确的格式

with(rle(position), split(lengths, values))
# $`-1`
# [1] 1 5
# 
# $`0`
# [1] 2 1
# 
# $`1`
# [1] 3 2

而且,要进行平均,tapply 会起作用

with(rle(position), tapply(lengths, values, FUN=mean))
#  -1   0   1 
# 3.0 1.5 2.5 

【讨论】:

  • 如果你喜欢这种方法,但更喜欢data.frame而不是array输出,你可以通过with(rle(position), aggregate(lengths ~ values, FUN = mean))使用aggregate
【解决方案2】:

您也可以将dplyrdiff 一起使用:

library(dplyr)
data %>% mutate(group = c(0, cumsum(diff(position)!=0))) %>% 
         group_by(position) %>%
         summarise(mean = n()/length(unique(group)))

Source: local data frame [3 x 2]

  position  mean
     (int) (dbl)
1       -1   3.0
2        0   1.5
3        1   2.5

【讨论】:

    【解决方案3】:

    有点冗长,但这显示了所有这些是如何结合在一起的:

    library(dplyr)
    position <- c(1, 1, 1, 0, 0, -1, 0, -1, -1, -1, -1, -1, 1, 1)
    rle_pos <- rle(position)
    
    df <- data_frame(position_code = rle_pos$values,
                     length = rle_pos$lengths)
    
    df
    # Source: local data frame [6 x 2]
    # 
    #   position_code length
    #           (dbl)  (int)
    # 1             1      3
    # 2             0      2
    # 3            -1      1
    # 4             0      1
    # 5            -1      5
    # 6             1      2
    
    df %>%
      group_by(position_code) %>%
      summarise(count = n(),
                sum_lengths = sum(length)) %>%
      mutate(average = sum_lengths / count)
    
    # Source: local data frame [3 x 4]
    # 
    #   position_code count sum_lengths average
    #           (dbl) (int)       (int)   (dbl)
    # 1            -1     2           6     3.0
    # 2             0     2           3     1.5
    # 3             1     2           5     2.5
    

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      相关资源
      最近更新 更多