【问题标题】:How to calculate the time difference between column 2 and 4, but under certain circumstances between column 3 and 4如何计算第 2 列和第 4 列之间的时间差,但在某些情况下在第 3 列和第 4 列之间
【发布时间】:2021-02-17 15:28:33
【问题描述】:

如何计算以下问题的时差:

数据

n1 <- as.factor(c('yes', 'yes', 'no', 'yes', 
                    'yes', 'no', 'yes', 'yes'))

n2 <- as.POSIXct(c('2006-12-10 13:01:22', '2006-12-11 12:13:11', 
                   '2006-12-12 13:12:11', '2006-12-13 11:01:22', 
                   '2006-12-14 15:13:11', '2006-12-15 13:12:11',
                   '2006-12-16 16:13:12', '2006-12-17 14:12:12'))

n3 <- as.POSIXct(c('2006-12-10 16:00:22', '2006-12-11 13:12:11', 
                   '2006-12-12 15:11:11', '2006-12-13 14:01:10', 
                   '2006-12-14 17:13:05', '2006-12-15 16:12:01',
                   NA, '2006-12-17 16:12:03'))

n4 <- as.POSIXct(c('2006-12-10 16:01:22', '2006-12-11 13:13:11', 
                   '2006-12-12 15:12:11', NA,
                   '2006-12-13 14:01:22', '2006-12-15 17:13:11', 
                   '2006-12-15 16:12:11', '2006-12-17 16:12:12'))

date <- data.frame(n1,
                   n2,
                   n3,
                   n4)

如果 n1 为“是”,则应计算 n2 和 n3 之间的时间差,但如果 n1 为“否”,则应在 n3 和 n4 之间计算时间差?两个计算应插入同一列。

【问题讨论】:

    标签: r time


    【解决方案1】:

    我们可以使用ifelse函数:

    date$newcol <- ifelse(date$n1 == "yes", 
                          difftime(date$n3, date$n2, units = "secs"), 
                          difftime(date$n4, date$n3, units = "secs"))
    

    这里,使用 dplyr 进行管道和mutate

    library(dplyr)
    date %>%
        mutate(newcol = ifelse(n1 == "yes", 
                               difftime(n3, n2, units = "secs"), 
                               difftime(n4, n3, units = "secs")))
    

    【讨论】:

    • 那行得通,但你也知道基于管道的解决方案吗?
    猜你喜欢
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多