Home > OS >  How to count the number of changes in ROW (R)
How to count the number of changes in ROW (R)

Time:06-02

df <- data.frame(Num1=c(1,0,1,0,1), Num2=c(0,1,1,0,1), Num3=c(1,1,1,1,1), Num4=c(1,1,0,0,1), Num5=c(1,1,1,0,0))

I need to count how many times value changes in each row in r. Thank you!

CodePudding user response:

rowSums(df[-1] != df[-ncol(df)])
[1] 2 1 2 2 1

ie first row there is a change from 1 to 0 then back to 1. so a total of 2 changes etc

CodePudding user response:

Here is a try ,

df <- data.frame(Num1=c(1,0,1,0,1), 
                 Num2=c(0,1,1,0,1),
                 Num3=c(1,1,1,1,1),
                 Num4=c(1,1,0,0,1),
                 Num5=c(1,1,1,0,0))


df$n_changes <- apply(df , MARGIN = 1 , function(x) sum(abs(diff(x))))

df
#>   Num1 Num2 Num3 Num4 Num5 n_changes
#> 1    1    0    1    1    1         2
#> 2    0    1    1    1    1         1
#> 3    1    1    1    0    1         2
#> 4    0    0    1    0    0         2
#> 5    1    1    1    1    0         1

Created on 2022-06-02 by the reprex package (v2.0.1)

CodePudding user response:

We may loop over the row with apply (MARGIN=1), then use rle (run-length-encoding), check the lengths

apply(df, 1, function(x) lengths(rle(x)))[1,]-1
[1] 2 1 2 2 1
  • Related