【问题标题】:How to save a filtered subset in R in a new column?如何将 R 中的过滤子集保存在新列中?
【发布时间】:2019-08-11 19:56:16
【问题描述】:

我有一个大的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 filter data-manipulation dplyr


    【解决方案1】:

    在基础 R 中 -

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

    dplyr -

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

    【讨论】:

    • 注意as.integer(test$mark == "R" &amp; test$test3 == "no")就够了
    猜你喜欢
    • 2021-10-05
    • 2015-04-04
    • 1970-01-01
    • 2016-09-23
    • 2020-03-09
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多