gpt4 book ai didi

根据另一列中的共识值替换列中的 NAs 值

转载 作者:行者123 更新时间:2023-12-04 02:27:46 26 4
gpt4 key购买 nike

我有一个数据框,例如:

Groups Event Value
G1 1 Canidae
G1 1 Canidae
G1 1 Felidae
G1 1 NA
G1 2 Felidae
G1 2 NA
G1 2 NA
G1 2 Felidae
G1 3 NA
G2 1 NA
G2 1 NA
G3 1 Lemuridae
G3 2 NA
G3 3 Lemuridae
G4 1 Felidae
G4 1 Felidae
G4 1 unknown
G5 1 unknown
G5 1 Felidae

我想在每个 GroupsEvent 中根据共识值,比如G1 Event1中有一个NA,那么共识值就是Canidae,所以我将 NA 替换为 Canidae

最后我应该得到:

Groups Event Value
G1 1 Canidae
G1 1 Canidae
G1 1 Canidae
G1 2 Felidae
G1 2 Felidae
G1 2 Felidae
G1 2 Felidae
G1 3 NA
G2 1 Lemuridae
G2 1 Lemuridae
G3 1 Lemuridae
G3 2 NA
G3 3 Lemuridae
G4 1 Felidae
G4 1 Felidae
G4 1 Felidae
G5 1 Felidae
G5 1 Felidae

有人有想法吗?非常感谢您的宝贵时间。

数据如下:

structure(list(Groups = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("G1", "G2",
"G3", "G4"), class = "factor"), Event = c(1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 1L, 1L, 1L, 2L, 3L, 1L, 1L, 1L), Value = structure(c(1L,
1L, 2L, NA, 2L, NA, NA, 2L, NA, NA, NA, 3L, NA, 3L, 2L, 2L, 4L
), .Label = c("Canidae", "Felidae", "Lemuridae", "unknown"), class = "factor")), class = "data.frame", row.names = c(NA,
-17L))

最佳答案

我们可以按模式进行分组

library(dplyr)
df1 %>%
mutate(Value = as.character(Value)) %>%
group_by(Groups, Event) %>%
mutate(Value = replace(Value, is.na(Value)|Value %in% "unknown",
Mode(Value[Value != "unknown"])))

在哪里

Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}

关于根据另一列中的共识值替换列中的 NAs 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66214757/

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