英文:
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 %>%
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
<chr> <chr> <chr> <chr>
1 4 1 8 2
2 6 2 4 1
3 missing 12 NA 2
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论