【问题标题】:Some Na values and not all一些 Na 值而不是全部
【发布时间】:2021-11-03 14:29:07
【问题描述】:

假设您有一个类似星球大战的数据集。还假设您有 2 列,其中一列具有 20 个 NA 值,另一列具有物种(人类、机器人、机器等)。

如何使用管道,仅将属于人类类别的na值转换为高度的平均值?

如果我们将其转换为总数,那将是错误的,因为机器可能会更小或更高,因此我们会得到一些奇怪的人类身高值。

附:我知道如何使用 replace 或 ifelse,但如何添加分类

【问题讨论】:

  • 欢迎使用 Stack Overflow。请阅读this post 了解如何生成可重复的示例,或阅读this one 了解如何在网站上提出一个好的问题。它会帮助人们帮助你。
  • 类似data %>% group_by(species) %>% mutate(heights = if_else(is.na(heights), mean(heights, na.rm = TRUE), heights))的东西

标签: r dplyr pipe


【解决方案1】:

在星球大战场景中,您可以执行以下操作

library(dplyr)

starwars %>% 
  group_by(species) %>% 
  mutate(height = if_else(species == "Human" & is.na(height), mean(height, na.rm = TRUE), as.double(height))) %>% 
  ungroup()

从这里可以看出,height 填充了仅人类作为物种的平均值

library(dplyr)

starwars %>% 
  group_by(species) %>% 
  mutate(newheight = if_else(species == "Human" & is.na(height), mean(height, na.rm = TRUE), as.double(height))) %>% 
  ungroup() %>% 
  select(species, height, newheight) %>% 
  filter(is.na(height))

#> # A tibble: 6 x 3
#>   species height newheight
#>   <chr>    <int>     <dbl>
#> 1 Human       NA      177.
#> 2 Human       NA      177.
#> 3 Human       NA      177.
#> 4 Human       NA      177.
#> 5 Droid       NA       NA 
#> 6 NA          NA       NA 

在这个特定示例中,您需要将height 转换为double,因为它是integer,并且由于if_else 是类型一致的,并且从mean 您会收到double,您需要相应地转换height。

【讨论】:

  • 谢谢你的解释,我还没想过双打!!
【解决方案2】:

如果我理解正确,您只是想通过组方式替换 NA?

应该这样做:

data(starwars)

head(starwars)

#This shows one missing value (NAs) for "Droid"
starwars %>%
  group_by(species) %>%
  summarize(M = mean(height, na.rm=T),
            NAs = sum(is.na(height)))

#Replace NAs by group-wise means
starwars <- starwars %>%
  group_by(species) %>%
  mutate(height = if_else(is.na(height), mean(height, na.rm=T), as.double(height) )) %>%
  ungroup()

#Now no missing value any more and means (M) remains the same
starwars %>%
  group_by(species) %>%
  summarize(M = mean(height, na.rm=T),
            NAs = sum(is.na(height)))

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多