【问题标题】:How to use mutate() to create multiple variables from function with vector output?如何使用 mutate() 从具有矢量输出的函数创建多个变量?
【发布时间】:2018-08-15 09:29:57
【问题描述】:

考虑一个包含 2 列的 tibble A,其中第 1 列包含时间戳(POSIXct 类)和一个 Interval 对象 b,它是我使用 lubridate::int_diff 创建的,包含 9 个单独的时间间隔。

使用 dplyr,我想在 tibble A 中添加 9 个新列,指示每行的时间戳是否在任何间隔内。换句话说,我想使用函数 %within% 并将长度为 9 的向量输出分布到 9 个新列中。

使用 dplyr 包最有效的是什么?

例子:

library(lubridate)
library(dplyr)

A <- tibble(Ts = ymd_hms(c("2018-01-01 15:12:04",
                       "2018-01-02 00:14:06","2018-01-05 12:00:00")),
        P = c(1:3))

ts.start <- ymd_hms("2018-01-01 15:00:00")
ts.end <- ymd_hms("2018-01-02 15:30:00")
ts <- c(ts.start,sort(ts.end - 
                    minutes(cumsum(c(15,15,30,30,60,60,60,60)))),ts.end)

b <- int_diff(ts)

# Applying %within" to the first element works
(A[[1,1]] %within% b) + 0

# The line with error.
mutate(A,New = Ts %within% b )

最后一行按预期产生错误,并且想知道如何根据在变量列上应用具有矢量输出的函数来定义新变量。

【问题讨论】:

    标签: r dplyr lubridate


    【解决方案1】:

    如何遍历Ts 的每个元素,检查它落在哪个区间内并将其附加到A

    # iterate through each element and output a list of matches for each element which
    # corresponds to a row
    out <- sapply(A$Ts, FUN = function(x, y) x %within% y, y = b, simplify = FALSE)
    
    # append result to original data
    cbind(A, do.call(rbind, out))
    
                       Ts P     1     2     3     4     5     6     7     8     9
    1 2018-01-01 15:12:04 1  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
    2 2018-01-02 00:14:06 2  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
    3 2018-01-05 12:00:00 3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
    

    您可以使用西葫芦图(只是编造的)来可视化该点属于哪个区间。

    library(ggplot2)
    
    xy <- data.frame(id = 1:length(b), start = int_start(b), end = int_end(b))
    head(xy)
    
    ggplot(xy) +
      theme_bw() +
      scale_fill_gradient(low = "#324706", high = "#aeb776") +
      geom_rect(aes(xmin = start, xmax = end, ymin = 0, ymax = nrow(A) + 0.5, fill = id),
                color = "white") +
      geom_hline(yintercept = A$P + 0.5, color = "grey") +
      geom_point(data = A, aes(x = Ts, y = P), color = "white", size = 2) +
      geom_point(data = A, aes(x = Ts, y = P), color = "black", size = 2, shape = 1)
    

    【讨论】:

    • 非常感谢您的回答。我现在编写了一个类似的工作,如果我能找到使用 mutate() 的解决方案,我会尝试。谢谢。阿恩
    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2021-06-13
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多