[英]Remove NAs from dataframe except in one column R
I have a dataframe: 我有一个数据框:
column1 <- c(400, 500, 350, 70, NA, NA, 500, 350, 70)
column2 <- c(NA, 67, 23, 45, 78, 123, 54, 123, 898)
column3 <- c(412, 4, 5, 6, 1, 689, 90, 12, NA)
column4 <- c("IMC", "VMC", NA, NA, NA, NA, "IMC", "VMC", "IMC")
data1 <- data.frame(column1, column2, column3, column4)
It looks like this: 看起来像这样:
column1 column2 column3 column4
400 NA 412 IMC
500 67 4 VMC
350 23 5 NA
70 45 6 NA
NA 78 1 NA
NA 123 689 NA
500 54 90 IMC
350 123 12 VMC
70 898 NA IMC
Question: Is it possible to remove the rows with NA's from column 1, 2 and 3, but not from column 4? 问题:是否可以从第1、2和3列中删除带有NA的行,但不能从第4列中删除? So my output will look like this:
所以我的输出将如下所示:
column1 column2 column3 column4
500 67 4 VMC
350 23 5 NA
70 45 6 NA
500 54 90 IMC
350 123 12 VMC
I have been struggling with this for a while now. 我已经为此苦了一段时间了。 Thanks!
谢谢!
You can use complete.cases()
on the first three columns and then do a subset
: 您可以在前三列中使用
complete.cases()
,然后执行一个subset
:
data1[complete.cases(data1[, 1:3]), ]
column1 column2 column3 column4
2 500 67 4 VMC
3 350 23 5 <NA>
4 70 45 6 <NA>
7 500 54 90 IMC
8 350 123 12 VMC
A library(dplyr)
approach : library(dplyr)
方法:
data1 %>% filter(complete.cases(.[,-4]))
or 要么
data1 %>% filter(complete.cases(.[,-3]))
if you want to keep NA's in column 3 如果您想将NA保留在第3列中
Here is an option using data.table
by specifying the columns in .SDcols
下面是使用选项
data.table
由指定的列.SDcols
library(data.table)
setDT(data1)[data1[, complete.cases(.SD), .SDcols = column1:column3]]
# column1 column2 column3 column4
#1: 500 67 4 VMC
#2: 350 23 5 NA
#3: 70 45 6 NA
#4: 500 54 90 IMC
#5: 350 123 12 VMC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.