Create ifelse function

Hi,

I have a dataset that looks like the following:

id<-c(1,1,2,2,2,3,3)
analysis<-c("CO","O","CO","CO","O","O","CO")
time<-c(1.5,2.1,1.2,33.6,24,71.9,72)
result<-c(5.4,14.1,7.0,3.2,12.3,15.5,4.3)

data<-data.frame(id,analysis,time,result)

I want to create a new column from analysis, time and result and have done so using the following:

data_CO0t<-data
data_CO0t$CO0t <- with(data_CO0t, ifelse(analysis == 'CO' &
time < 1 &
time >= 0,
result, NA))

data_CO0t <- subset(data_CO0t,CO0t!="NA")

data_CO1t<-data
data_CO1t$CO1t <- with(data_CO1t, ifelse(analysis == 'CO' &
time < 2 &
time >= 1,
result, NA))

data_CO1t <- subset(data_CO1t,CO1t!="NA")

data_CO2t<-data
data_CO2t$CO2t <- with(data_CO2t, ifelse(analysis == 'CO' &
time < 3 &
time >= 2,
result, NA))

data_CO2t <- subset(data_CO2t,CO2t!="NA")

data_CO <- merge(data_CO0t,data_CO1t,by=c("id"),all=TRUE)
data_CO<- merge(data_CO,data_CO2t,by=c("id"),all=TRUE)

Problem is, I want to this for time 0-72 in 1 hour intervals. There must be an easier way to do this instead of repeating it manually?

best wishes

Hi!

I am somewhat puzzled by what you are looking for, but it seems that you are trying to bin the results of your analysis within time buckets of 1 hr. In that case, why not use the cut() function to add a factor column which then can be aggregated, averaged or whatever?

library(dplyr)                                                      
                                                                    
id<-c(1,1,2,2,2,3,3)                                                
analysis<-c("CO","O","CO","CO","O","O","CO")                        
time<-c(1.5,2.1,1.2,33.6,24,71.9,72)                                
result<-c(5.4,14.1,7.0,3.2,12.3,15.5,4.3)                           
intervals  <- cut(time, breaks = seq(1,72, by = 1))                 
                                                                    
data<-data.frame(id,analysis,time,result, intervals)                
                                                                    
data %>% group_by(intervals, analysis) %>% summarize(mean(result))  
#   intervals analysis mean(result)                                 
# 1     (1,2]       CO          6.2                                 
# 2     (2,3]        O         14.1                                 
# 3   (23,24]        O         12.3                                 
# 4   (33,34]       CO          3.2                                 
# 5   (71,72]       CO          4.3                                 
# 6   (71,72]        O         15.5                                 

I hope this is somewhat what you are looking for. Otherwise, please provide a proper reprex and be more specific on what you are trying to accomplish.

JW