📜  在 R 中用 NA 替换字符值

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

在 R 中用 NA 替换字符值

在本文中,我们将看到如何在 R 编程语言中用 NA 替换字符值。

我们可以在向量和数据帧中用 NA 替换字符值。

示例 1:向量中的NA 替换字符值

在向量中,我们可以使用索引操作来替换它。

句法:

R
# create a vector with 10 characters
vector = c("a", "d", "A", "g", "S", 
           "S", "t", "S", "e", "S")
  
# store actual vector in final
final = vector
  
# replace character S with NA
final[final == "S"] <- NA 
  
# display final vector
print(final)


R
# create a dataframe with 10 characters
data = data.frame("a", "d", "A", "g", "S",
                  "S", "t", "S", "e", "S")
  
# store actual datarame in final
final = data
  
# replace character A with NA
final[final == "A"] <- NA 
  
# display final dataframe
print(final)


输出:

[1] "a" "d" "A" "g" NA  NA  "t" NA  "e" NA

示例 2:在数据框中用 NA 替换字符值

用数据帧中的 NA 替换字符值。

句法:

电阻

# create a dataframe with 10 characters
data = data.frame("a", "d", "A", "g", "S",
                  "S", "t", "S", "e", "S")
  
# store actual datarame in final
final = data
  
# replace character A with NA
final[final == "A"] <- NA 
  
# display final dataframe
print(final)

输出:

X.a. X.d. X.A. X.g. X.S. X.S..1 X.t. X.S..2 X.e. X.S..3
1    a    d     g    S      S    t      S    e      S