Robert Weber
Robert Weber

Reputation: 41

How do I count how many times this vector changes from 1 to 2 for a certain condition?

This is an example of a part of my data:

S.T.R      Num.

S           1
R           2
T           1
S           2
S           3
S           1
T           1
S           2
S           1
R           2

I want to count the number of times that Num. changes from 1 to 2 and the S.T.R value that is assigned to that 1. So, the number of times that an S's 1 or a T's 1 led to a 2. Up until now I have been counting these happenings by hand but would like to find a way to do it in R.

Upvotes: 0

Views: 101

Answers (2)

Andrew Gustar
Andrew Gustar

Reputation: 18425

In base-R, if df is your dataframe, then define a column of the next values like this...

df$Next <- c(df$Num.[-1],NA)

df
   S.T.R Num. Next
1      S    1    2
2      R    2    1
3      T    1    2
4      S    2    3
5      S    3    1
6      S    1    1
7      T    1    2
8      S    2    1
9      S    1    2
10     R    2   NA

Then you can use the table function to cross tabulate S.T.R against Next for those rows for which Num==1...

table(df$S.T.R[df$Num.==1],df$Next[df$Num.==1])

    1 2
  S 1 2
  T 0 2

So there are two 1-2 transitions for each of S and T. You might want to ignore the 1 column, which is the count of those that stay as 1.

Upvotes: 1

www
www

Reputation: 39154

A solution using .

library(dplyr)

dat2 <- dat %>%
  filter(`Num.` == 1 & lead(`Num.` == 2)) %>%
  count(`S.T.R`)
dat2
# # A tibble: 2 x 2
#   S.T.R     n
#   <chr> <int>
# 1 S         2
# 2 T         2

The total number would be sum(dat2$n), which is 4.

DATA

dat <- read.table(text = "S.T.R      Num.
S           1
R           2
T           1
S           2
S           3
S           1
T           1
S           2
S           1
R           2",
                  header = TRUE, stringsAsFactors = FALSE)

Upvotes: 2

Related Questions