Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 基于另一个单元格中的值操作组中的单元格_R_Dplyr_Tidyverse - Fatal编程技术网

R 基于另一个单元格中的值操作组中的单元格

R 基于另一个单元格中的值操作组中的单元格,r,dplyr,tidyverse,R,Dplyr,Tidyverse,我有一个data.frame,格式如下: CowId Bacillus Week 1234 1 Week1 1234 0 Week2 1234 0 Week3 1234 0 Week4 如果奶牛在第1周呈芽孢杆菌阳性(yes=1,no=0),那么我想将此列中的剩余值更改为1,如下所示: CowId Bacillus Week 1234 1

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

CowId    Bacillus    Week
1234     1           Week1
1234     0           Week2
1234     0           Week3
1234     0           Week4
如果奶牛在第1周呈芽孢杆菌阳性(yes=1,no=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)

感谢您的评论/反馈。

使用
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
#一个tible:8 x 3
#组别:CowId[2]
枯草芽孢杆菌周
1234 1周1
2 1234 1周2
3 1234 1周3
4 1234 1周4
5 1235 0周1
6 1235 0周2
7 1235 0周3
8 1235 0周4
使用的一些数据:

#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")
#数据

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

df$
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")