【问题标题】:Hot deck imputation in dplyrdplyr 中的热卡插补
【发布时间】:2014-07-02 19:28:47
【问题描述】:

我正在尝试使用 dplyr 包在 R 中进行热卡插补。我想用从同一组中抽取的随机值替换非有限值。

myData <- data.frame(value = sample(c(Inf, NaN, 1:8), 100, replace=TRUE), 
                     group = sample(letters[1:4], 100, replace=TRUE))
  value group
1     4     c
2     6     d
3   Inf     c
4     8     c
5     7     a
6     2     b

此代码运行但也会对 Inf 和 NaN 值进行采样。

myData <- myData %>%
  group_by(group) %>%
  mutate(imputedvalue = sample(value, n(), replace = TRUE))

table(is.finite(myData$imputedvalue), is.infinite(myData$imputedvalue))

        FALSE TRUE
  FALSE    16    7
  TRUE     77    0

这段代码没有运行。

myData <- myData %>%
  group_by(group) %>%
  mutate(imputedvalue = ifelse(is.finite(value), value, 
                               sample(value, n(), replace = TRUE)))
Error in n() : This function should not be called directly

我觉得应该有某种filter() 命令,但我真的不明白它应该如何工作......

【问题讨论】:

  • 你想要sample(value[is.finite(value)], sum(!is.finite(value)), T)
  • @eddi 我是按照这些思路思考的,但是当我在ifelse 中尝试它时,我意识到由于随机样本向量的长度与value 向量不同,回收开始发挥作用。为了保证每个非有限值的唯一随机抽取,我必须对组的size 进行抽样。
  • @aosmith 你说得对,我想更多的是分配给value[!is.finite(value)]

标签: r dplyr


【解决方案1】:

这是一种涉及首先拆分数据集的方法:

# filter non-infinite records

myDataOK <- myData %>%
  filter(value %>% is.finite)

# how many replacements are needed? 
# sample these, a la @eddi

myDataimputed <- myData %>%
  group_by(group) %>%
  summarise(n_inf = sum(!is.finite(value))) %>% 
  group_by(group) %>%
  do(sample_n(filter(myDataOK,group == .$group),size = .$n_inf,replace = TRUE))

## and combine!
myData2 <- rbind(myDataOK,myDataimputed)

## here are some various checks:

## same size as original?
nrow(myData2) == nrow(myData)

## all infinites replaced?
with(myData2,table(is.finite(value), is.infinite(value)))

## should be no *decreases* after shuffling.  
## value x block combinations might increase but should never decrease
check1 <- myDataOK %>% 
  group_by(group,value) %>%
  tally %>%
  arrange(group,value)
check2 <- myData2 %>% 
  group_by(group,value) %>%
  tally %>%
  arrange(group,value)
if(any((check2$n-check1$n) < 0)) stop("something went wrong!")


## finally, the increases in group size should equal the number of missing values

Ninf <- myData %>%
  group_by(group) %>%
  summarise(n_inf = sum(!is.finite(value)))

if(any(tally(check2)$n - tally(check1)$n - Ninf$n_inf !=0) ) 
  stop("group sizes changed!")

【讨论】:

  • 为什么投反对票?我所做的只是更正了 OP 代码中的一个错误!
  • 你正在用 same 值替换组中的所有非有限元素
  • 哦,我喜欢这段代码的干净程度。但由于某种原因,它比上面的ifelse 方法慢...
  • @AndrewMacDonald 新版本更改了value 的有限值并为一些数据而死;我不认为它符合 OP 的要求
  • @eddi 如何更改它们?而且,死于什么样的数据?我跑了几次,它总是有效(OP的数据每次都不一样
猜你喜欢
  • 2019-04-18
  • 2020-03-31
  • 2021-12-14
  • 2019-02-05
  • 2018-10-30
  • 1970-01-01
  • 2021-06-08
  • 2011-12-26
  • 1970-01-01
相关资源
最近更新 更多