【问题标题】:Extract data based on a list of time points from different individuals根据来自不同个体的时间点列表提取数据
【发布时间】:2022-01-24 03:26:39
【问题描述】:

我正在尝试根据不同个体所需的时间点列表来提取数据集的行。在 base R 中的实现方式是什么?

这是原始数据集:

data.frame(id=rep(1:3, each=3), time=1:3, y=c(1:9))

这是我想用来提取数据的每个 id 的时间点列表:

$`1` #this is id 1
 [1] 1 2 #these are the time points I need for id 1

$`2`
 [1] 1 3

$`3`
 [1] 2 3

所以最终的数据是这样的:

  id time y
   1    1 1
   1    2 2
   2    1 4
   2    3 6
   3    2 8
   3    3 9

【问题讨论】:

    标签: r indexing data-manipulation data-cleaning


    【解决方案1】:

    这里有几种遵循相同逻辑的方法。

    在基础 R 中 -

    do.call(rbind, Map(function(p, q) subset(data, id == q & time %in% p), 
            lst, names(lst)))
    

    或者使用tidyverse -

    library(dplyr)
    library(purrr)
    
    purrr::imap_dfr(lst, ~data %>% filter(id == .y, time %in% .x))
    
    #  id time y
    #1  1    1 1
    #2  1    2 2
    #3  2    1 4
    #4  2    3 6
    #5  3    2 8
    #6  3    3 9
    

    数据

    data <- data.frame(id=rep(1:3, each=3), time=1:3, y= 1:9)
    lst <- list(`1` = c(1, 2), `2` = c(1, 3), `3` = c(2, 3))
    

    【讨论】:

    • 像魅力一样工作。谢谢@Ronak Shah!
    • 嗨@Ronak Shah。对不起,另一个后续问题:如果我在lst 中有重复的时间点怎么办?例如,lst &lt;- list(1` = c(1, 1, 2), 2 = c(1, 3, 3), 3 = c(2, 2, 3)). It seems that the rows with repeated time points under the same id are removed by your code (is that the problem caused by %in% `?)。我如何仍然保留那些重复的行?
    【解决方案2】:

    一种使用左连接的方法:

    df <- data.frame(id=rep(1:3, each=3), time=1:3, y=c(1:9))
    want <- data.frame(id = rep(1:3, each = 2), 
                       time = c(1,2,1,3,2,3))
    
    merge(want, df, all.x = TRUE)      
    

    结果

      id time y
    1  1    1 1
    2  1    2 2
    3  2    1 4
    4  2    3 6
    5  3    2 8
    6  3    3 9
    

    【讨论】:

    • (我不太确定将您的列表转换为数据框的最佳方法。可能稍后再回来弄清楚。)
    • 谢谢@Jon Spring。确切地说,最好我想绕过将列表转换为数据框,因为我需要多次复制此过程,并且据说数据框可能会减慢速度。但无论如何,我赞成你的回答!
    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2014-07-01
    • 2015-11-09
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多