0

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

Seyma Kalay
  • 1,643
  • 8
  • 15
  • 1
    Don't use `cbind` unless you explicitly want data to be a matrix. In most of the cases dealing with dataframe is better so use `df – Ronak Shah Apr 08 '20 at 09:14

4 Answers4

2

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)
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
2

Using base R

df[ df$v2 == 0, "v2"] = NA
Tur
  • 574
  • 3
  • 9
1

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

linog
  • 5,350
  • 3
  • 13
  • 23
1

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)
RaV
  • 557
  • 1
  • 3
  • 10