1

Below is a snippet of data I am working with.

Flu
Day Positive Total
1 2 2
2 1 3
3 2 5
4 0 5
5 3 8
6 4 12
7 7 19
8 8 27
9 9 36
10 15 41

I am trying to write a loop with an if/else statement to determine if the one value in the Positive column is either "Higher" or "Lower" than the previous value. Doing so would then create a new column named "Trend" and would populate the row accordingly with "Higher" or Lower"

 {
if(Flu$Positive[i+1]>Covid$Positive[i]))
   Trend = "Higher"
else
   Trend = "Lower"
   }
  • 2
    Does this answer your question? [Basic lag in R vector/dataframe](https://stackoverflow.com/questions/3558988/basic-lag-in-r-vector-dataframe) – DanY Apr 27 '20 at 19:07

2 Answers2

0

We can use diff to create the logical vector

with(Covid, c("Lower", "Higher")[c(FALSE, diff(Positive) > 0) + 1])
#[1] "Lower"  "Lower"  "Higher" "Lower"  "Higher" "Higher" "Higher" "Higher" "Higher" "Higher"

If we need a loop, initiate an output vector with 'Lower' values, then loop over the sequence of rows, check if the current value of 'Positive' is greater than the previous row values, assign the vector for that row to 'Higher'

v1 <- rep("Lower", nrow(Covid))
for(i in 2:nrow(Covid)) if(Covid$Positive[i] > Covid$Positive[i-1]) v1[i] <- "Higher"
v1
# [1] "Lower"  "Lower"  "Higher" "Lower"  "Higher" "Higher" "Higher" "Higher" "Higher" "Higher"

data

Covid <- structure(list(Day = 1:10, Positive = c(1L, 0L, 1L, 0L, 1L, 2L, 
4L, 5L, 7L, 14L), Total = c(1L, 1L, 2L, 2L, 3L, 5L, 9L, 14L, 
21L, 35L)), class = "data.frame", row.names = c(NA, -10L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    this seems more smooth then a loop would be. It did work for my dataset, however, for my own sake of trying to understand how to write a loop, how would I write this as loop – Thomas Reilly Apr 28 '20 at 14:14
0

You can use the lag function to do it like so:

Covid$New <- ifelse(Covid$Positive > lag(Covid$Positive, 1L),"Higher","Lower")

**Please note that with higher and lower only you are not addressing "Same", which is one of the conditions.

Covid <- structure(list(Day = 1:10, Positive = c(1L, 0L, 1L, 0L, 1L, 2L, 
4L, 5L, 7L, 14L), Total = c(1L, 1L, 2L, 2L, 3L, 5L, 9L, 14L, 
21L, 35L)), class = "data.frame", row.names = c(NA, -10L))

Covid$NewCol <- ifelse(Covid$Positive > lag(Covid$Positive, 1L),"Higher","Lower")

print(Covid)
   Day Positive Total    New
1    1        1     1   <NA>
2    2        0     1  Lower
3    3        1     2 Higher
4    4        0     2  Lower
5    5        1     3 Higher
6    6        2     5 Higher
7    7        4     9 Higher
8    8        5    14 Higher
9    9        7    21 Higher
10  10       14    35 Higher
Edi Itelman
  • 423
  • 5
  • 14