📜  在 R DataFrame 的一列中删除带有 NA 的行

📅  最后修改于: 2022-05-13 01:54:49.486000             🧑  作者: Mango

在 R DataFrame 的一列中删除带有 NA 的行

R 编程语言中的 DataFrame 列可以具有由NA表示的空值。在本文中,我们将看到如何删除一列中带有 NA 的行。我们将看到各种删除具有 NA 值的行的方法。

使用中的数据:

方法

  • 创建数据框
  • 根据要删除的行选择列
  • 遍历列搜索 na 值
  • 选择行
  • 使用特定方法删除此类行

方法一:使用 drop_na()



drop_na() 删除值等于 NA 的行。要使用这种方法,我们需要使用可以安装的“tidyr”库。

句法:

例子:

R
# Creating dataframe
student=data.frame(name=c("Ram","Geeta","John","Paul",
                          "Cassie","Jim","Dwight")
                   ,maths=c(7,8,NA,9,10,8,9)
                   ,science=c(5,7,6,8,NA,7,8)
                   ,history=c(7,NA,7,7,NA,7,7))
  
print(student)
  
library(tidyr)
student %>% drop_na(maths)


R
# Creating dataframe
student=data.frame(name=c("Ram","Geeta","John","Paul",
                          "Cassie","Jim","Dwight")
                   ,maths=c(7,8,NA,9,10,8,9)
                   ,science=c(5,7,6,8,NA,7,8)
                   ,history=c(7,NA,7,7,NA,7,7))
  
print(student)
  
student[!is.na(student$science),]


R
# Creating dataframe
student=data.frame(name=c("Ram","Geeta","John","Paul",
                          "Cassie","Jim","Dwight")
                   ,maths=c(7,8,NA,9,10,8,9)
                   ,science=c(5,7,6,8,NA,7,8)
                   ,history=c(7,NA,7,7,NA,7,7))
  
print(student)
  
student[complete.cases(student$history),]


输出:



方法二:使用 is.na()

is.na()函数首先在列中查找 na 值,然后丢弃这些行。

句法:

例子:

电阻

# Creating dataframe
student=data.frame(name=c("Ram","Geeta","John","Paul",
                          "Cassie","Jim","Dwight")
                   ,maths=c(7,8,NA,9,10,8,9)
                   ,science=c(5,7,6,8,NA,7,8)
                   ,history=c(7,NA,7,7,NA,7,7))
  
print(student)
  
student[!is.na(student$science),]

输出:

方法三:使用complete.cases()

这个函数的作用和上面两种方法类似

句法:

例子:

电阻

# Creating dataframe
student=data.frame(name=c("Ram","Geeta","John","Paul",
                          "Cassie","Jim","Dwight")
                   ,maths=c(7,8,NA,9,10,8,9)
                   ,science=c(5,7,6,8,NA,7,8)
                   ,history=c(7,NA,7,7,NA,7,7))
  
print(student)
  
student[complete.cases(student$history),]

输出: