去除特定列R中的NA

虽然在这个论坛上已经提出了很多这样的问题,但我已经解决了其中的大部分问题,我的问题有点不同。我有一个数据框:

A  B  C  key
NA NA NA LIMA
3  1  NA GAMMA
NA NA NA SIGNA
NA 2  NA BETA
NA NA 4  SIGMA

我想删除特征集(A、B、C)上有 NA 的行。键永远不会为空,也永远不会有缺失值。所以生成的框架看起来像:

A  B  C  key
3  1  NA GAMMA
NA 2  NA BETA
NA NA 4  SIGMA

可以从下面复制类似数据帧的结构

structure(list(A = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), B = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), C = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), D = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), E = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), F = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), G = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), H = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), I = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), J = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), K = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), L = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), M = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), N = c(NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_), O = c(0, 2, NA, NA, 1, 1), P = c(NA_real_, 
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), Q = c(NA_real_, 
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), R = c(NA_real_, 
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), S = c(NA_real_, 
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), T = c(NA_real_, 
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), key = c("django", 
"lima", "bravo", "alpha", "gamma", 
"meta")), row.names = c(100077L, 93143L, 244634L, 25010L, 
117228L, 147983L), class = "data.frame")

任何帮助,将不胜感激。

回答

您可以使用rowSums

cols <- c('A', 'B','C')
df[rowSums(!is.na(df[cols])) != 0, ]

使用dplyr你可以使用across

library(dplyr)
df %>% filter(Reduce(`|`, across(all_of(cols), ~!is.na(.))))

  • There are ways to capture those columns but OP needs to clarify how the columns are stored in their data. For example based on position we can do `cols <- 1:3`. If their columns have some pattern we can use `grep` to get the index of the columns.

以上是去除特定列R中的NA的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>