简体   繁体   中英

add +1 to a column with condition in R

I have a dataframe called barometre2013 with a column called q0qc that contain this numbers:

[1] 15  1  9 15 9  3  6  3  3  6  6 10 15  6 15 10

I want to add +1 to the numbers that are >= 10, so the result should be this:

[1] 16  1  9 16 9  3  6  3  3  6  6 11 16  6 16 11  

I have tried this code:

if (barometre2013$q0qc > 9) {
  barometre2013$q0qc <- barometre2013$q0qc + 1
}

But this add +1 to all the numbers without respecting the condition:

[1] 16  2  10 16 10  4  7  4  4  7  7 11 16  7 16 11

How can I do what I want ?

Thank a lot.

When you executed:

if (barometre2013$q0qc > 9) {
  barometre2013$q0qc <- barometre2013$q0qc + 1
}

... you should have seen a warning about "only the first value being evaluated". That first value in barometre2013$q0qc was 15 and since it was TRUE, then that assignment was done on the entire vector. ifelse or Boolean logic are approaches suggested in the comments for conditional evaluation and/or assignment. The first:

barometre2013$q0qc <- barometre2013$q0qc + (barometre2013$q0qc >= 10) 

... added a vector of 1 and 0's to the starting vector; 1 if the logical expression is satisfied and 0 if not. If you wanted to add something other than one (which is the numeric value of TRUE) you could have multiplied that second term by the desired increment or decrement.

Another approach was to use ifelse which does do a conditional test of its first argument on returns either the second or third argument on an item-by-item basis:

barometre2013$q0qc <- barometre2013$q0qc + ifelse(barometre2013$q0qc >= 10, 1, 0)

The third approach suggested by dash2 would be to only modify those values that meet the condition. Note that this method requires having the "test vector on both sides of the assignment (which is why dash2 was correcting the earlier comment:

barometre2013$q0qc[barometre2013$q0qc>=10] <- 
                      barometre2013$q0qc[barometre2013$q0qc>=10]+ 1
    data <- c(15,1,9,15,9,3,6,3,3,6,6,10,15,6,15,10)

    data2 <- 

    as.numeric( 
      for(i in data){
      if(i >= 10){ i = i +1 }
      print(i)
      }
    )

class(data)
class(data2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM