dplyr跨表格与缺失值(更新至2022年)

huangapple go评论65阅读模式
英文:

dplyr cross tab with missing values (updated 2022)

问题

以下是已经翻译好的部分:

https://stackoverflow.com/questions/29108431/dplyr-cross-tab-with-missing-values

代码:

library(tidyr)
mtcars %>%
  mutate(
    cyl = ifelse(cyl > 6, NA, cyl),
    gear = ifelse(gear > 4, NA, gear)
  ) %>%
  group_by(cyl, gear) %>%
  tally() %>%
  ungroup() %>%
  mutate_each(funs(replace(., is.na(.), 'missing'))) %>%
  spread(gear, n)

建议代码中似乎存在一些已弃用的函数(mutate_each、funs 和 spread),所以遗憾的是它不能正常工作。

我正在尝试通过R来完成与Stata中通常做的相同的事情。

尝试运行原始帖子中的代码。

英文:

Would it be possible to update the answer given here:

https://stackoverflow.com/questions/29108431/dplyr-cross-tab-with-missing-values

code:

library(tidyr)
mtcars %>%
  mutate(
    cyl = ifelse(cyl > 6, NA, cyl),
    gear = ifelse(gear > 4, NA, gear)
  ) %>%
  group_by(cyl, gear) %>%
  tally() %>%
  ungroup() %>%
  mutate_each(funs(replace(., is.na(.), 'missing'))) %>%
  spread(gear, n)

There appear to be some deprecated functions (mutate_each, funs and spread) in the suggested code so sadly it doesn't work.

I'm trying to get up to speed with R doing the same things I normally do with Stata.

Tried to run the code as per original post.

答案1

得分: 1

library(tidyr); library(dplyr)
mtcars %>%
  mutate(
    cyl = ifelse(cyl > 6, NA, cyl),
    gear = ifelse(gear > 4, NA, gear)
  ) %>%
  count(cyl, gear) %>%
  mutate(across(everything(), ~coalesce(as.character(.), "missing"))) %>%
  pivot_wider(names_from = gear, values_from = n)

A tibble: 3 × 4

cyl 3 4 missing

1 4 1 8 2
2 6 2 4 1
3 missing 12 NA 2


<details>
<summary>英文:</summary>

    library(tidyr); library(dplyr)
    mtcars %&gt;%
      mutate(
        cyl = ifelse(cyl &gt; 6, NA, cyl),
        gear = ifelse(gear &gt; 4, NA, gear)
      ) %&gt;%
      count(cyl, gear) %&gt;%
      mutate(across(everything(), ~coalesce(as.character(.), &quot;missing&quot;))) %&gt;%
      pivot_wider(names_from = gear, values_from = n)

    # A tibble: 3 &#215; 4
      cyl     `3`   `4`   missing
      &lt;chr&gt;   &lt;chr&gt; &lt;chr&gt; &lt;chr&gt;  
    1 4       1     8     2      
    2 6       2     4     1      
    3 missing 12    NA    2  

</details>



huangapple
  • 本文由 发表于 2023年2月16日 17:31:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定