[英]How to remove na's from a select group of columns?
非常新手 R 用戶在這里。 我有一個數據集,並希望避免大量減少我的數據集(如果我使用 na.omit 或 complex.cases,它會刪除所有包含 na 的行,這會大大縮小我的數據集)。 我只想刪除與我的項目直接相關的列中的 na。 可以說第 1 列和第 2 列是相關的。 我嘗試使用 foo2 <- na.omit(foo1[-3:-4]) 但遇到錯誤“警告,在 3:4 中,數值表達式有 2 個元素,只會使用第一個元素” .
我想從這個 go
column 1 column 2 column 3 column 4
1 NA 4 3 9
2 5 NA NA 10
3 8 10 NA 4
4 11 6 2 NA
對此
column 1 column 2 column 3 column 4
3 8 10 NA 4
4 11 6 2 NA
因此,它沒有刪除每一行,而是只刪除了第 1 行和第 2 行。
先感謝您。
我們可以使用complete.cases
在列子集上返回一個邏輯向量(TRUE/FALSE - 對應於行中沒有 NA/任何 NA),並將其用作行索引來子集整個數據集
df1[complete.cases(df1[c('column1', 'column2')]),]
# column1 column2 column3 column4
#3 8 10 NA 4
#4 11 6 2 NA
應用於列子集的na.omit
僅返回該子集數據沒有任何 NA 的數據,而不是完整數據集。
df1 <- data.frame(column1=c(NA,5,8,11),column2=c(4,NA,10,6),
column3=c(3,NA,NA,2),column4=c(9,10,4,NA))
將df
定義為 dataframe,您可以確定 column1 和 column2 都不是 NA 的行,然后進行選擇:
df <- data.frame(column1=c(NA,5,8,11),column2=c(4,NA,10,6),column3=c(3,NA,NA,2),column4=c(9,10,4,NA))
df[with(df, !is.na(column1) & !is.na(column2)),]
column1 column2 column3 column4
3 8 10 NA 4
4 11 6 2 NA
您可以使用drop_na
package 中的tidyr
:
library(tidyr) # alternatively, you can load it from the tidyverse package
df <- tibble(
col1 = c(NA_real_, 5, 8, 11),
col2 = c(4, NA_real_, 10, 6),
col3 = c(3, NA_real_, NA_real_, 2),
col4 = c(9, NA_real_, 4, NA_real_)
)
drop_na(df, col1, col2)
# # A tibble: 2 x 4
# col1 col2 col3 col4
# <dbl> <dbl> <dbl> <dbl>
# 1 8 10 NA 4
# 2 11 6 2 NA
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.