Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

ifelse statement to compute if value is greater than its previous value

$
0
0

I am trying to compute the change from the previous day for each group.

Say I have these observations:

       cat var1 var2       date
1     male  172   68 2011-01-01
2   female   61  141 2011-01-02
3   female  211  208 2011-01-03
4    other   10   95 2011-01-04
5   female  149   49 2011-01-05

I want to add a new column with a 0 or 1 if the current var1 is greater or not than its previous result using an ifelse statement.

       cat var1 var2       date   NEWCOL
1     male  172   68 2011-01-01     -
2   female   61  141 2011-01-02     -
3   female  211  208 2011-01-03     1   # since its greater than 61
4   female   10   95 2011-01-04     0   # since its less than 211
5   female  149   49 2011-01-05     1   # since its greater than 10

Data:

tt <- seq(from = as.Date('2011-01-01', format = "%Y-%m-%d"), to = as.Date('2011-07-31', format = "%Y-%m-%d"), by = 1)

df <- data.frame(
  cat = sample(c('male', 'female', 'other'), length(tt), replace=TRUE),
  var1 = sample(length(tt), replace = TRUE),
  var2 = sample(length(tt), replace = TRUE),
  date = as.Date(tt)
)

EDIT: This does not work:

df %>% 
  mutate(var1 = as.numeric(var1)) %>% 
  group_by(cat, date) %>% 
  mutate(chng = first(var1) - last(var))

Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>