【问题标题】:select single value based on multiple attributes/col values in data frame in r [duplicate]根据r中数据框中的多个属性/列值选择单个值[重复]
【发布时间】:2021-04-05 03:05:13
【问题描述】:

这应该是一个常见问题,但我只能找到一个答案复杂的老问题here。假设我有一张航班延误表,我想根据directionweek 等属性选择特定的delay 时间?

df<- data.frame(
  Quarter = paste0("Q", rep(1:4, each = 4)),
  Week = rep(c(1:8), each = 2, times = 1),
  Direction = rep(c("Inbound", "Outbound"), times = 8),
  Delay = c(10.8, 9.7, 15.5, 10.3, 11.8, 8.9, 5.5,
            3.3, 10.6, 8.8, 6.6, 5.2, 9.1, 7.3, 5.3, 4.4)
)

上述帖子的建议答案如下所示:df[df[,"Week"]=="1" &amp; df[,"Direction"]=="Outbound","Delay"]。有没有更好的方法来做到这一点而无需重复数据框名称,在 tidyverse 中更简单?我想一次选择一个 single 元素,比如用[[进行子集化

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以使用filterselect

    library(dplyr)
    
    df %>%
      filter(Quarter == 'Q1', Direction == 'Inbound') %>%
      select(Delay)
    
    #  Delay
    #1  10.8
    #2  15.5
    

    如果您需要向量作为输出,请使用 pull 而不是 select


    在基础 R 中,您可以这样做:

    subset(df, Quarter == 'Q1' & Direction == 'Inbound', select = Delay)
    

    【讨论】:

    • 您好,谢谢您的回答。我稍微修改了我的 q。我的例子不准确。我想选择单个元素,而不是子集或数据框。我看到subset 和/或带有select 的管道会返回一个列表。
    • 修改后的版本有何不同?你可以做 df %&gt;% filter(Week == 1, Direction == 'Outbound') %&gt;% pull(Delay)subset, subset(df, Week == 1 &amp; Direction == 'Outbound')$Delay 。这就是你想要的吗?
    • 列表包含变量的名称。但我只想得到号码。所以基本上在我使用subset之后,我仍然需要使用[[来提取号码。 &gt; result[[1]] [1] 10.8
    • 如果你使用我上面result &lt;- subset(df, Week == 1 &amp; Direction == 'Outbound')$Delay评论中的代码,你不需要[[
    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多