-3

"multiple actions after if statement" Is there a way to make it simple?
The dataframe abnormal contains multiple cols, including Lab, v1, v2, v3, v4, v5, v6; I want to do is if Lab == "2018AV" for example, then I want assign v1 = "20x3", v2 ="7x3", v3="8x3"..... that is mean only this row will change.

if (abnormal$Lab in c("2018AV")) {abnormal$v1="20x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v2="7x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v3="8x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v4=NA}
if (abnormal$Lab in c("2018AV")) {abnormal$v5=NA}
if (abnormal$Lab in c("2018AV")) {abnormal$v6=NA}
puppetshow
  • 25
  • 5
  • 3
    `if (condition) { expr1; expr2; expr3 } else { expr4; expr5; expr6; }` – r2evans Mar 30 '18 at 02:22
  • Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Mar 30 '18 at 08:10
  • 1
    This is not R `abnormal$Lab in c("2018AV")`, it should be `%in%` or, better yet, since it is just one value, `==`. And `c("2018AV")` is the same as `"2018AV"`. Use `c()` for vectors with several elements – Rui Barradas Mar 30 '18 at 14:05

1 Answers1

1

Your question is a bit obscure. Is this what you wanted?

for (i in 1:nrow(abnormal)){
    if (abnormal$Lab[i] == "2018AV"){
        abnormal$v1[i] = "20x3"
        abnormal$v2[i] = "7x3"
        abnormal$v3[i] = "8x3"
        abnormal$v4[i] = NA
        abnormal$v5[i] = NA
        abnormal$v6[i] = NA
    }
}

or assuming that you are updating all the columns in your data frame ...

if ("2018AV" %in% abnormal$Lab) {
    abnormal[abnormal$Lab == "2018AV",] <- 
                                     c("2018AV", "20x3", "7x3", "8x3", NA, NA, NA)
}
Deepak Rajendran
  • 358
  • 1
  • 11
  • 2
    In the latter codeblock, you could even dispense with the if-statement. If the conditional in `[]` doesn't match anything, nothing happens. – JAD Mar 30 '18 at 08:14
  • @JAD I tried to factor for the existence of the value being filtered upon. If the value does not exist, running the assignment command in `[]` will result in a Warning message: `invalid factor level, NA generated` – Deepak Rajendran Mar 30 '18 at 08:24
  • Thanks. I tried the first code, but the whole col of v1 are "20x3" and v2 are "7x3". I only want to the rows with Lab == "2018AV" have this value. – puppetshow Mar 31 '18 at 00:48
  • I just wanted to show how you can write multiple lines of logic within the `if` statement. I wasn't concentrating on the correctness of the logic. I've now updated the first code to update the values of only those rows where Lab = "2018AV". – Deepak Rajendran Mar 31 '18 at 03:05
  • Thanks .But I have an error message: Error in if (abnormal[i, "Lab"] == "2018AV") { : missing value where TRUE/FALSE needed – puppetshow Mar 31 '18 at 14:50