r - 根据来自多个变量的多个观察值用 3 个可能的字符串填充一个变量
问题描述
我正在尝试使用以下数据和代码来实现这一目标:
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))
我想根据'diveLocation'(如果diveLocation ='Compliance'然后是那些行,类似地如果diveLocation ='Lease'然后那些行)和其他变量的观察来填充最后两个变量(nonComp 和nonCompLease)。我尝试了以下代码:
#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", "no", "no", "no", "no", "no") nonCompLease = c("yes", "yes", "yes ", "yes", "yes", "yes", "FALSE")) 而它应该是:nonComp = c("yes", "no", "no", NA, NA, NA, NA) nonCompLease = c(不适用,不适用,不适用,“否”,“否”,“是”,“是”))
任何有关编码以获得所需结果的帮助将不胜感激
解决方案
修改后的代码显示了您想要的内容:
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
推荐阅读
- excel - 复选框和下拉列表的触发器不能同时工作
- python - Python:CountVectorizer 上的 ValueError。Series 的真值是模棱两可的
- c - C 编程 - 航空公司预订系统 - 为什么我的保存文件功能不起作用?
- c++ - 字符串不适用于 if else 语句
- ios - Cordova 混合应用程序:单击时不会触发汉堡菜单选项
- php - Json 循环内的 Laravel 查询
- javascript - 反应在正确的位置和大小显示日历事件
- python - 如何绑定多数据库 python 数据库编码/数据库?
- power-automate - 该应用程序需要从基于平板电脑的应用程序和 Smartsheet 单元格中提取信息,并使用该数据填充 Microsoft Word 文档
- python - 在调用 Python 函数时不定义其他可选参数后,有没有办法定义可选参数?