简体   繁体   中英

How to calculate the number of specific observation each row and add to the last column in R?

Let's say I have a data frame like this:

ID <- c('A','B','C','D')
P1 <- c(1,1,0.1,0.2)
P2 <- c(0.7,1,0.6,0.4)
P3 <- c(0.9,0.9,0.9,0.9)
P4 <- c(1,1,0.9,0.5)
df <- data.frame(ID,P1,P2,P3,P4)


  ID  P1  P2  P3  P4 
1  A 1.0 0.7 0.9 1.0      
2  B 1.0 1.0 0.9 1.0      
3  C 0.1 0.6 0.9 0.9      
4  D 0.2 0.4 0.9 0.5      

Now I'd like to calculate how many items in A are less than 1, and add the number to the last new column, so does B, C, D

so that the final result looks like this:

    ID  P1  P2  P3  P4 number
  1  A 1.0 0.7 0.9 1.0      2
  2  B 1.0 1.0 0.9 1.0      1
  3  C 0.1 0.6 0.9 0.9      4
  4  D 0.2 0.4 0.9 0.5      4

Does anyone know how to do this?

You can try colSums , ie

rowSums(df2[-1] < 1)
#P1 P2 P3 P4 
# 2  3  4  2 

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