首页 > 解决方案 > 根据另一列的值替换列中的 NA

问题描述

我有一个如下的数据框:

    name<-c("Fred","George","","Fred","George")
wif<-c("fd","gf",NA,NA,NA)
asv<-c("hj","fd",NA,NA,NA)
wdf<-c("bn","jk",NA,NA,NA)
label<-c("Fred","George","","Fred","George")
fam<-data.frame(name,wif,asd,wdf,label)

如您所见,前 2 行与后 2 行完全相同,但wife1wife2wife3值是NAs. 中间有空白值,NAs应该保持这样。我想用与前 2 行相同的值填充最后 2 行。请注意,该解决方案应应用于具有不同行数的数据集中。

我试过fam %>% group_by(name) %>% mutate_all(~ .[!is.na(.)])但我得到:

mutate_all()` ignored the following grouping variables:
Column `name`
Use `mutate_at(df, vars(-group_cols()), myoperation)` to silence the message.
Error: Column `wife1` must be length 1 (the group size), not 0

标签: r

解决方案


您可以将名称列与其自身匹配以获取名称第一次出现的索引,并将该行中的值用于要修改的列。

cols <- 2:4 # or if your column names contain a pattern: grep(pattern, names(fam))
fam[cols] <- fam[match(fam$name, fam$name), cols]

fam
#     name wife1 wife2 wife3  label
# 1   Fred    fd    hj    bn   Fred
# 2 George    gf    fd    jk George
# 3         <NA>  <NA>  <NA>       
# 4   Fred    fd    hj    bn   Fred
# 5 George    gf    fd    jk George

推荐阅读