-2

I want to set the value 6 to the variable "M3_rankin_factor" when "M3_mortalite" variable is equal to 1.

  summary(M2clean$M3_rankin_factor)  
   0    1    2    3    4    5    6 NA's
 176   71   44   31   52   29    3   71 


  summary(M2clean$M3_mortalite)
Non  Oui NA's 
402   34   41 


  for (i in rownames(M2clean)) {if(!is.na(M2clean$M3_mortalite[i]) && M2clean$M3_mortalite == 1) M2clean$M3_rankin_factor[i] <- 6}


  summary(M2clean$M3_rankin_factor)
   0    1    2    3    4    5    6 NA's 
 176   71   44   31   52   29    3   71 

I don't understand

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • Thank you very much, but it doesn't work. I want to keep the 6 classes and this formule recode into 2 classes : summary(M2clean$M3_rankin_factor) 1 2 NA's 402 34 41 – mimiryudo Apr 15 '15 at 09:11
  • Can you post result of `dput(M2clean)`? and see [reproducible-example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – zx8754 Apr 15 '15 at 09:13
  • It's a big database: I can extract the whole text from the console and paste here... I read the reproducible-example, thank you. – mimiryudo Apr 15 '15 at 09:17
  • How about `str(M2clean)` or `dput(head(M2clean))`, so we know more about the data... – zx8754 Apr 15 '15 at 09:20

3 Answers3

1

Try this

M2clean$M3_rankin_factor[M2clean$M3_mortalite == 1] <- 6
dimitris_ps
  • 5,849
  • 3
  • 29
  • 55
0

You can use

M2clean$M3_rankin_factor[which(M2clean$M3_mortalite==1)] <- 6

as long as 1 and 6 are valid factor levels for the variables involved.
Using which instead of M2clean$M3_mortalite==1 you avoid the NA problem.
I've tested it: it works on factor too

f <- as.factor(c(NA,1,2,3))
#[1] <NA> 1    2    3
f[which(f==1)] <- 3
#[1] <NA> 3    2    3 
ruggero
  • 442
  • 3
  • 7
0

Thank you, it works. An another answer :

M2clean[M2clean$M3_mortalite == "Oui" & (!is.na(M2clean$M3_mortalite)), "M3_rankin_factor"] <- 6