简体   繁体   中英

r function if else assign value to variable

fdI'm working with R and this is my dilemma.

The gist of the story is I"m taking two different times, splitting the times in the middle and would like to create a separate column with the split times. I have that worked out with this formula:

 burglary$midtime <- as.POSIXct((as.numeric(burglary$BegDate) + as.numeric(burglary$EndDate)) / 2, origin = '1970-01-01')

The hiccup is not all the times have and end time. So if it doesn't have and end time I want to populate it with just the beginning time. I came up with teh below if / else statement but it just populates the column with the split times and leaves the others blank.

if(!is.null(burglary$EndDate)) { 
    burglary$midtime <- as.POSIXct(burglary$BegDate)
} else {
    burglary$midtime <- as.POSIXct((as.numeric(burglary$BegDate) +    
        as.numeric(burglary$EndDate)) / 2, origin = '1970-01-01')
}

Any idea what I'm doing wrong?

Taylor H, thank you for pointing me in the right direction. The ifelse statment worked but it decimated the date and time turning it to numbers.

I ended up using the dplyr library library(dplyr) which kept the date and time intact. Final code is below. Again, thanks for the assistance!

burglary$midTime <- if_else(!is.na(burglary$EndDate), as.POSIXct((as.numeric(burglary$BegDate) + as.numeric(burglary$EndDate)) / 2, origin = '1970-01-01'), as.POSIXct(burglary$BegDate))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM