简体   繁体   English

r函数,否则为变量赋值

[英]r function if else assign value to variable

fdI'm working with R and this is my dilemma. fd我正在使用R,这是我的难题。

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. 并非所有时间都有打and和结束时间。 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 / else语句中想出了这个方法,但是它只是将拆分时间填充到该列中,而其他列保留为空白。

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. 泰勒·H,谢谢您为我指明了正确的方向。 The ifelse statment worked but it decimated the date and time turning it to numbers. ifelse语句有效,但是它减少了将日期和时间转换为数字的日期和时间。

I ended up using the dplyr library library(dplyr) which kept the date and time intact. 我最终使用了dplyr库library(dplyr) ,该library(dplyr)使日期和时间保持完整。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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