我试图使用以下数据和代码来实现这一点:
beg.new <-c(1, 0, 0, 0, 2, 3, 3)
GasBubbles<-c(0, 0, 0, 0, 0, 1, 2)
PF<- c(0, 0, 0, 1, 1, 0, 0)
debris<-c(0, 1, 0, 0, 0, 1, 0)
diveLocation<-c('Compliance', 'Compliance', 'Compliance', 'Lease',
'Lease', 'Lease', 'Lease')
nonComp<- NA
nonCompLease<- NA
df=data.frame(beg.new, GasBubbles, PF, debris, diveLocation, nonComp,
nonCompLease)提供数据:
structure(list(beg.new = c(1, 0, 0, 0, 2, 3, 3), GasBubbles = c(0,
0, 0, 0, 0, 1, 2), PF = c(0, 0, 0, 1, 1, 0, 0), debris = c(0,
1, 0, 0, 0, 1, 0), diveLocation = structure(c(1L, 1L, 1L, 2L,
2L, 2L, 2L), .Label = c("Compliance", "Lease"), class = "factor"),
nonComp = c(NA, NA, NA, NA, NA, NA, NA), nonCompLease = c(NA,
NA, NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA,
-7L))我希望填充最后两个变量(nonComp和nonCompLease),这取决于' diveLocation‘(如果diveLocation =’diveLocation‘那么这些行,以及类似地如果diveLocation= 'Lease’那么这些行)和其他变量的观察。我试过了折页码:
#first noncompliance where diveLocation=='Compliance'
df$nonComp <- if(df$diveLocation=='Compliance' & df$beg.new==1&
df$beg.new==2& df$beg.new==3& df$GasBubbles==1& df$GasBubbles==2& df$PF==1&
df$PF==2& df$PF==3){
print('yes')
}else{
print('no')
}和
#2nd noncompliance where diveLocation=='Lease'
df$nonCompLease <- ifelse(df$diveLocation=='Lease'& df$beg.new==3 &
df$GasBubbles==2, df$PF==3, 'yes')不幸的是,我得到了: nonComp = c("no","no") nonCompLease =c(“是”,“FALSE”),而它应该是: nonComp =c(“是”,“否”,“否”,“不”) nonCompLease = c(NA,"no","no",“no”),(“是的”))
如果您能在编码方面提供任何帮助以获得所需的结果,将不胜感激。
发布于 2019-01-07 12:38:42
经过修改的代码,它显示了您希望它做的事情:
library(tidyverse)
df2 <- as_tibble(df)
df3 <- df2 %>%
mutate(nonComp = case_when(diveLocation == "Compliance" & (beg.new %in% c(1, 2, 3) | GasBubbles == 2 | PF %in% c(1, 2, 3)) ~ "Yes",
diveLocation == "Lease" ~ NA_character_,
TRUE ~ "No")) %>%
mutate(nonCompLease = case_when(diveLocation == "Lease" & (beg.new == 3 | GasBubbles == 2 | PF == 3) ~ "Yes",
diveLocation == "Compliance" ~ NA_character_,
TRUE ~ "No"))df3是:
# A tibble: 7 x 7
beg.new GasBubbles PF debris diveLocation nonComp nonCompLease
<dbl> <dbl> <dbl> <dbl> <fct> <chr> <chr>
1 1 0 0 0 Compliance Yes NA
2 0 0 0 1 Compliance No NA
3 0 0 0 0 Compliance No NA
4 0 0 1 0 Lease NA No
5 2 0 1 0 Lease NA No
6 3 1 0 1 Lease NA Yes
7 3 2 0 0 Lease NA Yes https://stackoverflow.com/questions/54067420
复制相似问题