Ashit Trivedi
Ashit Trivedi

Reputation: 5

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?

Upvotes: 0

Views: 335

Answers (2)

sds
sds

Reputation: 60074

If you have a data.frame f, then you can do

f$MDV[f$DV > 0] <- 0

to set MDV to zero whenever DV is positive.

Upvotes: 2

Rich Scriven
Rich Scriven

Reputation: 99381

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

Upvotes: 0

Related Questions