【问题标题】:subset a dataframe on multiple conditions in R在 R 中对多个条件下的数据帧进行子集化
【发布时间】:2021-02-16 19:44:49
【问题描述】:

我的数据集有几个变量,我想构建一个子集并根据这些条件创建新变量

dat1 
S1 S2 H1 H2 Month1 Year1 Month2 Year2
16 17 81 70  09   2017   07      2017
17 16 80 70  08   2017   08      2016
14 16 81 81  09   2016   05      2016
18 15 70 81  07   2016   09      2017
17 16 80 80  08   2016   05      2016
18 18 81 70  05   2017   04      2016

我想进行子集化,如果 S1=16,17,18 和 H1=81,80 那么我创建一个新变量 Hist=H1 , date=paste(Month1,Year1) Sip = S1 S2, H2 的集合也是如此。 我的输出应该是:[前 4 行来自 S1、H1、Month1、Year2 的集合,最后 2 行来自 S2、H2、Month2、Year2

Hist Sip Date
81   16  09-2017
80   17  08-2017
80   17  08-2016
81   18  05-2017
81   16  05-2016
80   16  05-2016

我的代码:

datnew <- dat1 %>%
 mutate(Date=ifelse((S1==16|S1==17|S1=18)&(H1==80|H1==81),paste(01,Month1,Year1,sep="-"),
                      ifelse((S2==16|S2==17|S2==18)&(H2==80|H2==81),paste(Month2,Year2,sep="-"),"NA")),
      hist=ifelse((S1==16|S1==17|S1=18)&(H1==80|H1==81),H1,
                  ifelse((S2==16|S2==17|S2==18)&(H2==80|H2==81),H2,"NA")),
      sip=ifelse((S1==16|S1==17|S1=18)&(H1==80|H1==81),S1,
                  ifelse((S2==16|S2==17|S2==18)&(H2==80|H2==81),S2,"NA"))) 

在原始数据中,我有 10 组这样的列,即 S1-S10、H1-H10、Month1_-Month10... 对于每个变量,我都有更多的数字条件。 在这种方法中,它一直在进行。有没有更好的方法来做到这一点?

提前致谢

【问题讨论】:

  • 您的mutate() 尝试究竟是什么样的。通过修复你开始的事情而不是从头开始来帮助你通常更容易。

标签: r if-statement subset


【解决方案1】:

这是tidyverse 解决方案。分成两个数据框并将行绑定在一起。

library(tidyverse)
  
bind_rows(
  dat1 %>% select(patientId, ends_with("1")) %>% rename_all(str_remove, "1"),
  dat1 %>% select(patientId, ends_with("2")) %>% rename_all(str_remove, "2")
) %>%
  transmute(
    patientId,
    Hist = H,
    Sip = S,
    date = paste0(Month, "-", Year)
  ) %>%
  filter(
    Sip %in% 16:18,
    Hist %in% 80:81
  )
#> # A tibble: 6 x 4
#>    patientId  Hist   Sip date   
#>        <int> <dbl> <dbl> <chr>  
#> 1          1    81    16 09-2017
#> 2          2    80    17 08-2017
#> 3          5    80    17 08-2016
#> 4          6    81    18 05-2017
#> 5          3    81    16 05-2016
#> 6          5    80    16 05-2016

【讨论】:

  • 是 - 将 patientId 添加到 selects 和 transmute。我已更新我的答案以包含此内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2021-05-29
  • 2015-06-20
  • 2022-06-18
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多