-3

I have a column with values which represent the temperature of every hour in a day. What I am trying to do is to change every value less than 18 to a 0. But if there is at least one value for each 24 rows (hours) that is greater than 18, I want to change all 24 values to 1.

Is there any function or loop that I can use for this problem?

  • 2
    you should look at [How to make a great R reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). It is hard to answer your question without any data or what you have already tried. – tbradley Mar 05 '17 at 16:15

2 Answers2

1

you can do following:

set.seed(1)
df <- data.frame(matrix(round(runif(24*24,1,19)), nrow = 24, ncol = 24))
colnames(df) <- paste("hour_", 1:24)
df[df < 18] <- 0 # change all values < 18 to 0
df[apply(df, 1, function(x) sum(x > 18) > 0), ] <- 1 # change all 24 values to 1
Codutie
  • 1,055
  • 13
  • 25
1
#DATA
set.seed(42)
df = data.frame(Day = ceiling(1:240/24),
                Hour = 0:239 %% 24,
                Value = sample(c(15,20), 240,
                prob = c(0.95 ,0.05),
                replace = TRUE))

#Run ave and obtain max for each group of 24 values (in this example, it's grouped by 'Day')
as.numeric(ave(df$Value, df$Day, FUN = max) > 18)
d.b
  • 32,245
  • 6
  • 36
  • 77