count columns with same value/string for each row in r

后端 未结 2 1533
太阳男子
太阳男子 2021-01-24 19:07

Say my data(imaginary) ,a data frame is as follows :

 > head(data)
                       mpg_H cyl_G disp_G  
    Mazda RX4         TRUE   TRUE     TRUE              


        
相关标签:
2条回答
  • You can use apply and sum.

    df$count_TRUE <- apply(df, 1,sum); 
    df$count_FALSE <- (ncol(df)-1)-df$count_TRUE;
    
    0 讨论(0)
  • 2021-01-24 19:44

    Try rowSums or Reduce

    count_TRUE <- rowSums(df) # Or count_TRUE <- Reduce(`+`, df)
    df[c("count_TRUE", "count_FALSE")] <- cbind(count_TRUE, ncol(df) - count_TRUE)
    df
    #                   mpg_H cyl_G disp_G count_TRUE count_FALSE
    # Mazda RX4          TRUE  TRUE   TRUE          3           0
    # Mazda RX4 Wag      TRUE FALSE  FALSE          1           2
    # Datsun 710        FALSE FALSE  FALSE          0           3
    # Hornet 4 Drive    FALSE  TRUE   TRUE          2           1
    # Hornet Sportabout  TRUE  TRUE   TRUE          3           0
    # Valiant            TRUE  TRUE  FALSE          2           1
    
    0 讨论(0)
提交回复
热议问题