R is.na() Function - Detecting and Handling Missing Values

R 语言实例R Language Examples

The R is.na() function is used to detect which elements in a vector or data frame are missing values (NA).

Handling missing values is an essential step in data analysis, directly affecting the accuracy of analysis results.

The syntax of the is.na() function is as follows:

is.na(x)
anyNA(x)          # 检查是否存在任何 NA
complete.cases(x) # 检查哪些行没有 NA

Parameter description:

  • xThe vector, matrix, or data frame to be checked.

Example

# Detect NA in vector
x <- c(10, NA, 20, NA, 30, 40)
print("NA detection:")
print(is.na(x))
print(paste("Number of NA:", sum(is.na(x))))
print(paste("Contains NA:", anyNA(x)))

# Handle NA in data frame
df <- data.frame(
Name= c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu"),
Score= c(88, NA, 76, NA),
Age= c(25, 30, NA, 28)
)
print("\n"Data frame:")
print(df)

# Find complete rows (without NA)
print("Complete rows:")
print(df[complete.cases(df), ])

# Count the number of NA in each column
print("NA count per column:")
print(colSums(is.na(df)))

# Delete rows containing NA
df_clean <- na.omit(df)
print("\n"After removing NA:")
print(df_clean)

The output after executing the above code is:

[1] "NA 检测:"
[1] FALSE  TRUE FALSE  TRUE FALSE FALSE
[1] "NA 个数: 2"
[1] "是否有 NA: TRUE"

[1] "数据框:"
  姓名 成绩 年龄
1 张三   88   25
2 李四   NA   30
3 王五   76   NA
4 赵六   NA   28

[1] "完整行:"
  姓名 成绩 年龄
1 张三   88   25
[1] "每列 NA 数:"
姓名 成绩 年龄
   0    2    1

[1] "删除 NA 后:"
  姓名 成绩 年龄
1 张三   88   25

R 语言实例R Language Examples

Other Extensions