0

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?

5
  • Does the DV column really have a . in it? Commented Jun 16, 2014 at 18:40
  • Yes, it has '.' or '0' Commented Jun 16, 2014 at 18:41
  • Is it safe to assign NA to values that are .? Commented Jun 16, 2014 at 18:42
  • It is safe to assign '0' for '.' Commented Jun 16, 2014 at 18:44
  • I refuse to beleive that you did a minimal effort of finding an answer yourself and wasn't successful Commented Jun 16, 2014 at 20:56

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.