gpt4 book ai didi

r - 根据重复的 ID 变量删除 NA

转载 作者:行者123 更新时间:2023-12-01 23:41:51 30 4
gpt4 key购买 nike

我的数据看起来像这样

zz <- 'wb_iso3c                   country year wbclass
1: YUG "Serbia and Montenegro (former)" 1990 NA
2: YUG "Yugoslavia (former)" 1990 UM
3: YUG "Yugoslavia (former)" 1991 NA
4: YUG "Serbia and Montenegro (former)" 1991 UM
5: YUG "Serbia and Montenegro (former)" 1992 NA
6: YUG "Yugoslavia (former)" 1992 NA'
Data <- read.table(text=zz, header = TRUE)

在以下情况下,我想找到一种系统有效地放弃观察的方法:仅考虑 wb_iso3cyear,我的观察结果是重复的。 (因此我不关心另一个变量如 country 是否有不同的值)。在“重复”的观察中,我想保留wbclass 不是 NA 的观察结果。如果wbclass 对于两个观察结果都是 NA,保留哪一行是无关紧要的。

最终的数据集应该是这样的

   wb_iso3c                        country year wbclass
1: YUG Yugoslavia (former) 1990 UM
2: YUG Serbia and Montenegro (former) 1991 UM
3: YUG Serbia and Montenegro (former) 1992 <NA>

非常感谢您的帮助。如果能用dyplr的data.table就好了。

最佳答案

使用 dplyr,您可以尝试以下操作。

首先 group_by wb_iso3cyear,旨在为这两列的每个不同组合获取一个观察值。

然后排列(排序顺序)组内的wbclass 列。使用 arrangeNA 值将始终排序到末尾。

然后slice(1)会保留每组的第一行数据。

library(dplyr)

Data %>%
group_by(wb_iso3c, year) %>%
arrange(wbclass) %>%
slice(1)

输出

  wb_iso3c country                         year wbclass
<chr> <chr> <int> <chr>
1 YUG Yugoslavia (former) 1990 UM
2 YUG Serbia and Montenegro (former) 1991 UM
3 YUG Serbia and Montenegro (former) 1992 NA

关于r - 根据重复的 ID 变量删除 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64879290/

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