how to assign df$v2==0 as NA
v1 <- c("1","2","3","4","5")
v2 <- c("a","b","c","d","0")
df <- cbind(v1,v2)
df
Expected answer would be
v1 v2
[1,] "1" "a"
[2,] "2" "b"
[3,] "3" "c"
[4,] "4" "d"
[5,] "5" "NA"
many thanks in advance
how to assign df$v2==0 as NA
v1 <- c("1","2","3","4","5")
v2 <- c("a","b","c","d","0")
df <- cbind(v1,v2)
df
Expected answer would be
v1 v2
[1,] "1" "a"
[2,] "2" "b"
[3,] "3" "c"
[4,] "4" "d"
[5,] "5" "NA"
many thanks in advance
You could assign directly :
df$v2[df$v2 == 0] <- NA
df
# v1 v2
#1 1 a
#2 2 b
#3 3 c
#4 4 d
#5 5 <NA>
Or with replace
or ifelse
.
df$v2 <- replace(df$v2, df$v2 == 0, NA)
df$v2 <- ifelse(df$v2 == 0, NA, df$v2)
data
df <- data.frame(v1,v2, stringsAsFactors = FALSE)
You also have data.table
(recommended option if your dataset is voluminous) that uses update by reference (:=
operator)
dt <- data.table('v1' = v1,'v2' = v2)
dt[v2 == "0", v2 := NA_character_]
By the way, you use characters but it looks like you could use numeric format for v1
Since your df is actually a string matrix
, you can use:
df[df[, 2] == "0", 2] <- NA_character_
Output:
df
v1 v2
[1,] "1" "a"
[2,] "2" "b"
[3,] "3" "c"
[4,] "4" "d"
[5,] "5" NA
But I would recomend one of the data.frame
solutions posted here.
Data:
v1 <- c("1","2","3","4","5")
v2 <- c("a","b","c","d","0")
df <- cbind(v1,v2)