📜  用 R DataFrame 中的 NA 替换空白

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

用 R DataFrame 中的 NA 替换空白

在本文中,我们将看到如何在 R 编程语言中将数据帧中的空白替换为 NA。

示例 1: R 程序将数据帧中的空白替换为 NA

我们将使用基于“==”运算符的逻辑条件替换空单元格。

句法:

R
# create a dataframe with 4 rows and 2 columns
data = data.frame(col1 = c(1, 2, 3, ""),
                  col2 = c("", 4, 5, ""))
  
# store actual dataframe in final
final = data
  
# replace blank with NA
final[final == ""] <- NA 
  
# display final dataframe
print(final)


R
# create a dataframe with 4 rows and 2 columns
data = data.frame(col1 = c(1, 2, 3, " "),
                  col2 = c(" ", 4, 5, " "))
  
# store actual dataframe in final
final = data
  
# replace blank and space with NA
final[final == " "] <- NA 
  
# display final dataframe
print(final)


R
# create a dataframe with 4 rows and 2 columns
data = data.frame(col1 =c (1, 2, 3, ""),
                  col2 = c("", 4, " ", " "))
  
# store actual dataframe in final
final = data
  
# replace blank and blank space with NA
final[final == ""  | final== " "] <- NA 
  
# display final dataframe
print(final)


输出:

col1 col2
1    1 
2    2    4
3    3    5
4  

示例 2:R 程序在数据框中用 NA 替换空格和空格

电阻

# create a dataframe with 4 rows and 2 columns
data = data.frame(col1 = c(1, 2, 3, " "),
                  col2 = c(" ", 4, 5, " "))
  
# store actual dataframe in final
final = data
  
# replace blank and space with NA
final[final == " "] <- NA 
  
# display final dataframe
print(final)

输出:

col1 col2
1    1 
2    2    4
3    3    5
4  

示例 3:用 NA 替换空格和空格的 R 程序

如果我们想同时替换空格和空格,那么我们可以同时使用以 | 分隔的两个条件。运算符

句法:

电阻

# create a dataframe with 4 rows and 2 columns
data = data.frame(col1 =c (1, 2, 3, ""),
                  col2 = c("", 4, " ", " "))
  
# store actual dataframe in final
final = data
  
# replace blank and blank space with NA
final[final == ""  | final== " "] <- NA 
  
# display final dataframe
print(final)

输出:

col1 col2
1    1 
2    2    4
3    3 
4