简体   繁体   English

检查两列的条件,如果为true,则操纵R中的第三列

[英]Checking a condition on two columns and if true manipulate a 3rd column in R

I am been searching for an solution to this problem and have not been able to find one. 我一直在寻找解决此问题的方法,但找不到。 It is somewhat similar to other questions so if this is a duplicate I apologize. 这有点类似于其他问题,因此,如果这是重复的,我表示歉意。

I am looking to check two conditions on a dataframe and when both conditions are met change a third column. 我希望检查数据框上的两个条件,并且当两个条件都满足时,请更改第三列。 It may be easier to see with an example: 通过一个示例可能更容易看到:

greetings <- c("Hello", "Howdy", "Hola")

df <- data.frame(
  Criteria_1 = c("Hello", "Hello", "Goodbye", "Goodbye", "Hello"),
  Criteria_2 = c("Yes", "No", "Yes", "No", "Yes"),
  Change_col = c(1,5,6,9,3))

 Criteria_1 Criteria_2 Change_col
1      Hello        Yes          1
2      Hello         No          5
3    Goodbye        Yes          6
4    Goodbye         No          9
5      Hello        Yes          3

I would like to check if Criteria_1 has a value in the variable 'greeting' and if Criteria_2 is 'Yes'. 我想检查Criteria_1是否在变量“ greeting”中有一个值,以及Criteria_2是否为“是”。 When both are true I would like to change the value in 'Change_col' to 10. 当两者都为真时,我想将“ Change_col”中的值更改为10。

This is what I tried but it is changing all of the Change_col values to 10. 这是我尝试过的方法,但是它将所有Change_col值更改为10。

if(df$Criteria_1 %in% greetings & df$Criteria_2 == 'Yes'){
  df$Change_col <- '10'

I think I may have to use the apply function? 我想我可能必须使用apply函数? But not really sure how to do that. 但不是很确定该怎么做。 The desired output would be this: 所需的输出将是这样的:

  Criteria_1 Criteria_2 Change_col
1      Hello        Yes         10
2      Hello         No          5
3    Goodbye        Yes          6
4    Goodbye         No          9
5      Hello        Yes         10

We can use a logical expression to change the values in 'Change_col' to 10 我们可以使用逻辑表达式将“ Change_col”中的值更改为10

df$Change_col[with(df, Criteria_1 %in% greetings & Criteria_2 == "Yes")] <- 10
df
#  Criteria_1 Criteria_2 Change_col
#1      Hello        Yes         10
#2      Hello         No          5
#3    Goodbye        Yes          6
#4    Goodbye         No          9
#5      Hello        Yes         10

I think dplyr::mutate and the ifelse() statement offers a nice solution. 我认为dplyr::mutateifelse()语句提供了一个不错的解决方案。 Have you tried the following? 您是否尝试过以下方法?

library(tidyverse)

newDf <- df %>%
   mutate(Change_col = ifelse(Criteria_1 %in% greetings & Criteria_2 == "Yes", 10, Change_col))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM