R语言na.omit函数删除NA值实战

目录

R语言na.omit函数删除NA值实战

#基本语法

#dataframe应用na.omit

#删除向量中的NA值

#na.omit函数、complete.cases函数、is.na函数对比


#基本语法

na.omit(data)

#dataframe应用na.omit

data <- data.frame(x1 = c(9, 6, NA, 9, 2, 5, NA),     
# Column with 2 missing values
                   x2 = c(NA, 5, 2, 1, 5, 8, 0),      
                   # Column with 1 missing values
                   x3 = c(1, 3, 5, 7, 9, 7, 5))       
                   # Column without missing values
data                                                  
# Print data to RStudio console

Example Data with NA na.omit in R


data_omit <- na.omit(data)                            
# Apply na.omit in R
data_omit                                             
# Print data_omit to RStudio console

After Application of na omit R Function

#删除向量中的NA值

data$x1                                               
# Original data vector with NAs
# 9  6 NA  9  2  5 NA

na.omit(data$x1)                                      
# Vector without NAs
# 9 6 9 2 5
# attr(,"na.action")
# 3 7
# attr(,"class")
# "omit"

as.numeric(na.omit(data$x1))                          
# Vector without NAs & attributes
# 9 6 9 2 5

#na.omit函数、complete.cases函数、is.na函数对比

data_subset <- data[ , c("x1")]                       
# Create subset with important columns

data_by_column <- data[complete.cases(data_subset), ] 
# Omit NAs by columns
data_by_column                                        
# Print data_by_column to RStudio console

Omit NA Values by Columns

data_is.na <- data[!is.na(data$x1), ]                 
# Omit NA by column via is.na
data_is.na                                            
# Same result as with complete.cases


参考:NA Omit in R | 3 Example Codes for na.omit (Data Frame, Vector & by Column)

参考:statisticsglobe.com

参考:R

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐