更新
也许您只需要从“长”转向“宽”?
dat <- structure(list(District.Name = c("District 1", "District 1", "District 2", "District 2", "District 2", "District 2", "District 3", "District 3"), Course.Code = c("Course A", "Course A", "Course A", "Course B", "Course B", "Course D", "Course B", "Course C")), class = "data.frame", row.names = c(NA, -8L))
library(dplyr)
dat %>%
mutate(a = TRUE) %>%
tidyr::pivot_wider(names_from="Course.Code", values_from="a", values_fill=FALSE, values_fn=any)
# # A tibble: 3 x 5
# District.Name `Course A` `Course B` `Course D` `Course C`
# <chr> <lgl> <lgl> <lgl> <lgl>
# 1 District 1 TRUE FALSE FALSE FALSE
# 2 District 2 TRUE TRUE TRUE FALSE
# 3 District 3 FALSE TRUE FALSE TRUE
临时的a 列实际上只是一个占位符。必要的、暂时的、没有长期影响的。
上一个答案
我认为最好将逻辑分为两个步骤:(1)从excel文件中读取; (2) 过滤行。
第一个是直接使用readxl 或openxlsx 包。我将在此处显示两者都使用,但将使用dat2 作为其余答案。
dat1 <- openxlsx::readWorkbook("~/StackOverflow/14617210/Book1.xlsx", sheet = 1)
dat2 <- readxl::read_excel("~/StackOverflow/14617210/Book1.xlsx")
dat2
# # A tibble: 3 x 5
# `district name` `course A` `course B` `course C` `course D`
# <chr> <chr> <chr> <chr> <chr>
# 1 District 1 no yes yes no
# 2 District 2 no no no no
# 3 District 3 yes yes yes yes
注意事项:
您的第二个任务(过滤数据)在 R 的任何方言中都是直截了当的。我不清楚您的过滤逻辑究竟应该如何进行,因此我将演示几个变体。
-
显示那些包含 none 课程的地区(都是"no"):
# base R
dat2[rowSums(subset(dat2, select = `course A`:`course D`) == "yes") == 0, ]
# # A tibble: 1 x 5
# `district name` `course A` `course B` `course C` `course D`
# <chr> <chr> <chr> <chr> <chr>
# 1 District 2 no no no no
# dplyr
library(dplyr)
dat2 %>%
filter(across(`course A`:`course D`, ~ . == "no"))
-
显示至少有 1 个“否”的课程:
# base R
dat2[rowSums(subset(dat2, select = `course A`:`course D`) == "no") > 0, ]
# # A tibble: 2 x 5
# `district name` `course A` `course B` `course C` `course D`
# <chr> <chr> <chr> <chr> <chr>
# 1 District 1 no yes yes no
# 2 District 2 no no no no
# dplyr
dat2 %>%
filter(rowSums(across(`course A`:`course D`, ~ . == "no")) > 0)
示例数据,此处为 CSV,粘贴到电子表格中并保存为 Book1.xlsx:
district name,course A,course B,course C,course D
District 1,no,yes,yes,no
District 2,no,no,no,no
District 3,yes,yes,yes,yes