Change in state based on sorted variable in R

Viewed 49

I have a variable called "exposed" and I know already the sum of exposed people over time, "index" is how many people the individual meet in a week: have a look to understand

i exposed index
1 y 22
2 y 12
3 y 6
4 n 54
5 n 3

So I have 3 exposed individuals and 2 are not.

t <- 5
#I know that each i in t :

sum(exposed[i]) <- c(3,4,1,4,5)

I created this line of code to capture the change in data:

evol <- list()

for(i in 1:t){evol[[i]]<- df}

for (i in 2:t) {
  # condition

}

If the number of exposed at [t] is higher than the number of exposed at [t-1] so individuals with exposed==n and have a higher index change the exposed variable from n to y.

If the number of exposed at [t] is lower than the number of exposed in [t-1] so individuals with exposed==y and have the lower index change the exposed variable from y to n.

My question is: what is the condition that I have to write to have in:

A data set that looks like this:

evol[[1]]
i exposed index
1 y 22
2 y 12
3 y 6
4 n 54
5 n 3

should change to the data hat looks like this:

evol[[2]]
i exposed index
1 y 22
2 y 12
3 y 6
4 y 54
5 n 3

If the data looks like this:

evol[[3]]
i exposed index
1 n 22
2 n 12
3 n 6
4 y 54
5 n 3

I hope I made it clear;

Any ideas please;

kind regards.

1 Answers

Here is a function to change the vector exposed.

change_exposed <- function(exposed, index) {
  stopifnot(length(exposed) == length(index))
  for(i in seq_len(length(index))[-1L]) {
    if(index[i] > index[i - 1L]) {
      exposed[i] <- if(exposed[i] == "y") "n" else "y"
    }
  }
  exposed
}
change_exposed(evol[[1]]$exposed, evol[[1]]$index)
#[1] "y" "y" "y" "y" "n"

Assign the result to exposed to actually change the data set.

evol[[1]]$exposed <- change_exposed(evol[[1]]$exposed, evol[[1]]$index)
identical(evol[[1]], evol[[2]])
# [1] TRUE

Data

evol <- list()
x <- 'i     exposed     index
1   y   22
2   y   12
3   y   6
4   n   54
5   n   3'
evol[[1]] <- read.table(textConnection(x), header = TRUE)
x <- 'i     exposed     index
1   y   22
2   y   12
3   y   6
4   y   54
5   n   3'
evol[[2]] <- read.table(textConnection(x), header = TRUE)
Related