Ashit Trivedi Ashit Trivedi - 22 days ago 9
R Question

How to substitute values in one row column based on values in another column?

I have the following data:

#ID DV MDV#
1 2 1
2 3 0
3 0 0
4 . 0


I want the following:
Whenever DV column has a non-zero number, the MDV column should be 0 and vice-versa.
If DV has a zero value (or missing value), MDV should be 1 for that ID.

#ID DV MDV#
1 2 0
2 3 0
3 0 1
4 . 1


How do I code this?

Answer Source

ifelse might do the trick for you here.

Read your data:

> d <- read.table(h=T, text = "ID    DV    MDV
   1     2     1
   2     3     0
   3     0     0
   4     .     0", stringsAsFactors = FALSE)

Since "." > 0 is FALSE, we can reset the MDV column according to your specifications of the DV column as follows:

> d$MDV <- ifelse(d$DV > 0, 0, 1)
> d
#   ID DV MDV
# 1  1  2   0
# 2  2  3   0
# 3  3  0   1
# 4  4  .   1