-2

I'm trying to add a constant to a variable based on a value of another variable. In other words I have two variables (Cancer, psa). Cancer 1, 0 (which is yes no) if the patient has cancer I want to add 2.0 to another variable 'psa' which is continuous. If the patient does not have cancer I want to skip over their psa variable value and move to the next case. I think this is a if or ifelse but I'm not sure

My best guess so far: ifelse(cancer=1,(psa1=psa1+2),(psa1=psa1*1))

Stedy
  • 7,359
  • 14
  • 57
  • 77
Tom
  • 19
  • 1
  • 1
    hi! welcome to stackoverflow, please check out how to make a great reproducible example to get some ideas on how to improve your post: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example . it's also a bit unclear exactly what error you're getting, and what you've tried to correct it. your statement has a few syntax errors: first you are checking an equality with cancer so it should be `cancer==1`. second if your assignment operator `=` is in the wrong place. this (if your'e using dplyr) will work `mutate(psa1=ifelse(cancer==1,psa1+2,psa1)` – bjoseph Apr 09 '17 at 00:26
  • a simple `psa <- psa + 2*cancer` should do it – dww Apr 09 '17 at 01:17

1 Answers1

1

Without seeing your data its a little hard to tell what you want but here is a quick example using an ifelse:

R> sample_Data <- data.frame(cancer = sample(0:1, replace = T, 10), psa = sample(1:10))
R> sample_Data$psa1 <- ifelse(sample_Data$cancer == 1, sample_Data$psa + 2, sample_Data$psa * 1)
R> sample_Data
   cancer psa psa1
1       0   5    5
2       0   8    8
3       1   2    4
4       0  10   10
5       1   1    3
6       1   3    5
7       0   9    9
8       1   6    8
9       1   7    9
10      0   4    4
Stedy
  • 7,359
  • 14
  • 57
  • 77