In this article, we are going to see how to replace character value with NA in R Programming Language.
We can replace a character value with NA in a vector and in a dataframe.
Example 1: Replace Character Value with NA in vector
In a vector, we can replace it by using the indexing operation.
Syntax:
vector[vector == “character”] <- 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)
|
Output:
[1] "a" "d" "A" "g" NA NA "t" NA "e" NA
Example 2: Replace Character Value with NA in Dataframe
Replace character value with NA in dataframe.
Syntax:
dataframe[dataframe== “character”] <- NA
R
# create a dataframe with 10 characters data = data.frame ( "a" , "d" , "A" , "g" , "S" ,
"S" , "t" , "S" , "e" , "S" )
# store actual dataframe in final final = data # replace character A with NA final[final == "A" ] <- NA
# display final dataframe print (final)
|
Output:
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 <NA> g S S t S e S