r - 根据另一列的值替换列中的 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 行完全相同,但wife1
和wife2
和wife3
值是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
解决方案
您可以将名称列与其自身匹配以获取名称第一次出现的索引,并将该行中的值用于要修改的列。
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
推荐阅读
- firebase - 删除文档 Firestore 功能是否会引发未找到的异常?(扑)
- c - 从C中的输入值中找到奇数的阶乘
- cypress - 使用 cypress 查看网页证书
- c# - 使用 Windows 窗体将 C# 连接到 mySQL 数据库
- python - 如何仅使用我的 df 中的日期而不是所有日期进行绘图
- json - 如果我传递一个将在 Swift/Obj-C 中返回 JSON 的对象,如何创建一个通用类和函数?
- swift - SwiftUI:如何打开字体选择器?
- excel - 计算电力支点的月效率
- uwp - UWP:滚动 ListView 以专注于项目
- angular - 使用 OnPush 在 push/removeAt 后更新 Angular FormArray 内容