【问题标题】:Manipulating cells within a group based on value in another cell根据另一个单元格中的值操作组内的单元格
【发布时间】:2020-09-24 03:24:56
【问题描述】:

我有一个格式如下的data.frame:

CowId    Bacillus    Week
1234     1           Week1
1234     0           Week2
1234     0           Week3
1234     0           Week4

如果一头奶牛在第 1 周是芽孢杆菌阳性(是=1,否=0),那么我想将此列中的剩余值更改为 1,如下所示:

CowId    Bacillus    Week
1234     1           Week1
1234     1           Week2
1234     1           Week3
1234     1           Week4

我尝试了以下方法,但在确定第 1 周奶牛的感染状态后不确定如何进行:

dt %>%
    group_by(CowId) %>%
    mutate(Bacillus = ifelse(Week == "Week1" & Bacillus, 1,
                          ifelse(Week != "Week1" do something)

感谢任何 cmets/反馈。

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    使用any() 尝试这种方法并测试一周。我创建了虚拟数据来显示示例:

    library(dplyr)
    library(tidyr)
    #Code
    df %>% group_by(CowId) %>%
      mutate(Bacillus=ifelse(any(Bacillus[Week=='Week1']==1),1,0))
    

    输出:

    # A tibble: 8 x 3
    # Groups:   CowId [2]
      CowId Bacillus Week 
      <dbl>    <dbl> <chr>
    1  1234        1 Week1
    2  1234        1 Week2
    3  1234        1 Week3
    4  1234        1 Week4
    5  1235        0 Week1
    6  1235        0 Week2
    7  1235        0 Week3
    8  1235        0 Week4
    

    使用的一些数据:

    #Data
    df <- structure(list(CowId = c(1234, 1234, 1234, 1234, 1235, 1235, 
    1235, 1235), Bacillus = c(1, 0, 0, 0, 0, 0, 0, 0), Week = c("Week1", 
    "Week2", "Week3", "Week4", "Week1", "Week2", "Week3", "Week4"
    )), row.names = c(NA, -8L), class = "data.frame")
    

    【讨论】:

      【解决方案2】:

      base R中,我们可以用'Bacillus'&amp;'Week'创建一个逻辑向量,其值为'Week1',子集'CowId',检查它是否在'CowId'中,强制逻辑转二进制 (+)

      df$Bacillus <- with(df, +(CowId %in% unique(CowId[as.logical(Bacillus) &
                 Week == 'Week1'])))
      df$Bacillus
      #[1] 1 1 1 1 0 0 0 0
      

      数据

      df <- structure(list(CowId = c(1234, 1234, 1234, 1234, 1235, 1235, 
      1235, 1235), Bacillus = c(1, 0, 0, 0, 0, 0, 0, 0), Week = c("Week1", 
      "Week2", "Week3", "Week4", "Week1", "Week2", "Week3", "Week4"
      )), row.names = c(NA, -8L), class = "data.frame")
      

      【讨论】:

        猜你喜欢
        • 2019-10-04
        • 1970-01-01
        • 2013-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-31
        • 2012-05-15
        • 1970-01-01
        相关资源
        最近更新 更多