r - 如何将 R 中的过滤子集保存在新列中?
问题描述
我有一个很大dataframe
的 ,我想根据某些列(所有因素)进行过滤,并将过滤后的行另存为同一dataframe
. 所以我不想创建一个子集或删除行,我想将它们保持在同一个dataframe
. 例子:
## my dataframe:
test <- data.frame(name=c("alice", "brandon", "cedric", "dwayne"), mark = c("V", "R", "R", "R"), test3 = c("yes", "no", "yes", "no"))
## the filter I use for selecting
test %>% filter(mark == "R" & test3 == "no")
## what I want as added new column (filtered selection)
test$conclusion <- c(NA, "yes", NA, "yes")
tets$conclusion <- c(0,1,0,1) # would also be fine.
但我不知道该怎么做,除了dataframe
从过滤结果中创建一个新的,添加一个新列,并将新dataframe
的与旧的合并dataframe
。必须有一个更简单的解决方案。我尝试了 mutate,但我只能使用该函数计算一个新列。我试过了
test %>% filter(mark == "R" & test3 == "no") %>%
dplyr::mutate(.$conclusion == "yes")
但后来我得到这个错误:
mutate_impl(.data, dots) 中的错误:列 `.$conclusion == "yes"` 的长度必须为 4(行数)或 1,而不是 0。
感谢您的帮助和建议。
解决方案
在基础 R -
test$conclusion <- ifelse(test$mark == "R" & test$test3 == "no", 1, 0)
与dplyr
-
test %>%
mutate(conclusion = ifelse(mark == "R" & test3 == "no", 1, 0))
推荐阅读
- python - 如何在python中使用Falcon将客户端'GET'请求从一个API路由到另一个具有相同端点的API?
- javascript - 导出独立的 swagger-ui
- python - 图轴文本、刻度和标签
- r - 在 r 中创建一个与 end 匹配的序列
- android - Android Kotlin 从 Activity 中获取 Fragment 中的 Zxing 条码结果
- python - Pandas 聚合 - 如何根据活动日期查找最近的活动
- c# - 使用 Fiddler 和 Web REST API
- node.js - 为什么 Node.js 事件循环在空闲时这么慢?
- python - TensorFlow Data 不适用于多输入 keras 模型
- json - 使用 JQ 处理嵌套对象映射中的空值