gpt4 book ai didi

r - 如何根据条件获得 R 中多列的中位数(根据另一列)

转载 作者:行者123 更新时间:2023-12-04 10:27:36 25 4
gpt4 key购买 nike

我是 R 的初学者,我想知道如何执行以下任务:

我想用数据集所有列的中位数替换数据集的缺失值。
但是,对于每一列,我想要某个类别的中位数(取决于另一列)。我的数据集如下

structure(list(Country = structure(1:5, .Label = c("Afghanistan", 
"Albania", "Algeria", "Andorra", "Angola"), class = "factor"),
CountryID = 1:5, Continent = c(1L, 2L, 3L, 2L, 3L), Adolescent.fertility.rate.... = c(151L,
27L, 6L, NA, 146L), Adult.literacy.rate.... = c(28, 98.7,
69.9, NA, 67.4)), class = "data.frame", row.names = c(NA,
-5L))

所以对于每一列,我想用 中值的中位数替换缺失值特定大陆。

最佳答案

我们可以使用 dplyr::mutate_at替换 NA每列中的 s(除了 Continent 和非数字列 Country )及其 Continent 的中位数团体

df <- structure(list(Country = structure(1:5, .Label = c("Afghanistan",  "Albania", "Algeria", "Andorra", "Angola"), class = "factor"), 
CountryID = 1:5, Continent = c(1L, 2L, 3L, 2L, 3L),
Adolescent.fertility.rate.... = c(151L, 27L, 6L, NA, 146L),
Adult.literacy.rate.... = c(28, 98.7, 69.9, NA, 67.4)), class = "data.frame", row.names = c(NA, -5L))

library(dplyr)
df %>%
group_by(Continent) %>%
mutate_at(vars(-group_cols(), -Country), ~ifelse(is.na(.), median(., na.rm = TRUE), .)) %>%
ungroup()

返回:

  # A tibble: 5 x 5
Country CountryID Continent Adolescent.fertility.rate.... Adult.literacy.rate....
<fct> <int> <int> <int> <dbl>
1 Afghanistan 1 1 151 28
2 Albania 2 2 27 98.7
3 Algeria 3 3 6 69.9
4 Andorra 4 2 27 98.7
5 Angola 5 3 146 67.4


解释:
首先我们将 data.frame df 分组来自 Continent .然后我们按以下方式改变除分组列(和 Country 不是数字)之外的所有列:如果 is.na为真,我们将其替换为中位数,并且由于我们已分组,因此它将是 Continent 的中位数组(如果不是 NA,我们将其替换为它自己)。最后我们打电话 ungroup为恢复“正常”的良好措施 tibble .

关于r - 如何根据条件获得 R 中多列的中位数(根据另一列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60564823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com