首页 > 解决方案 > 如何将 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。

感谢您的帮助和建议。

标签: rfilterdata-manipulationdplyr

解决方案


在基础 R -

test$conclusion <- ifelse(test$mark == "R" & test$test3 == "no", 1, 0)

dplyr-

test %>%
  mutate(conclusion = ifelse(mark == "R" & test3 == "no", 1, 0))

推荐阅读