我有一个数据框架子集,如下所示。我想填写“疾病的年龄”栏中的NAs,以便一个患者的年龄与没有疾病的兄弟姐妹(从familyID鉴定)相同。

structure(list(id = c(1, 2, 3, 4, 5, 6),
familyId = c(1, 1, 2, 2, 3, 3),
disease = c(1, 0, 0, 1, 1, 0),
`age at disease` = c("40","NA", "NA", "43", "52", "NA")),
class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))这意味着最后一栏“疾病年龄”应为:C(40,40,43,43,52)。
发布于 2022-05-14 15:40:49
您可以使用以下代码:
library(dplyr)
library(tidyr)
df %>%
na_if("NA") %>%
group_by(familyId) %>%
fill(`age at disease`) %>%
fill(`age at disease`, .direction = "up")输出:
# A tibble: 6 × 4
# Groups: familyId [3]
id familyId disease `age at disease`
<dbl> <dbl> <dbl> <chr>
1 1 1 1 40
2 2 1 0 40
3 3 2 0 43
4 4 2 1 43
5 5 3 1 52
6 6 3 0 52 发布于 2022-05-14 15:57:16
如果每个组只有一个非NA元素,我们也可以这样做。
library(dplyr)
df1 %>%
type.convert(as.is = TRUE) %>%
group_by(familyId) %>%
mutate(`age at disease` = `age at disease`[complete.cases(`age at disease`)][1]) %>%
ungroup-output
# A tibble: 6 × 4
id familyId disease `age at disease`
<dbl> <dbl> <dbl> <chr>
1 1 1 1 40
2 2 1 0 40
3 3 2 0 43
4 4 2 1 43
5 5 3 1 52
6 6 3 0 52 发布于 2022-05-14 16:24:57
下面是另一种dplyr方法:
df %>%
group_by(familyId) %>%
arrange(`age at disease`,.by_group = TRUE) %>%
mutate(`age at disease` = first(`age at disease`)) id familyId disease `age at disease`
<dbl> <dbl> <dbl> <chr>
1 1 1 1 40
2 2 1 0 40
3 4 2 1 43
4 3 2 0 43
5 5 3 1 52
6 6 3 0 52 https://stackoverflow.com/questions/72241646
复制相似问题