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
  • 2,037
  • 10
  • 22
  • 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 <- data.frame(v1,v2, stringsAsFactors = FALSE)` to create dataframe. – 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
  • 377,200
  • 20
  • 156
  • 213
2

Using base R

df[ df$v2 == 0, "v2"] = NA
Tur
  • 604
  • 4
  • 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,786
  • 3
  • 14
  • 28
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
  • 617
  • 1
  • 5
  • 11