英文:
How to pass different lines of code based on multiple arguments in R?
问题
由于编辑太多而开启新会话。
我有一个数据框,看起来像这样:
df <- data.frame(ID = c("A","A","A","B","B","B","C","C","C"),
value = c(1,2,3,1,2,3,1,2,3))
我想要使用条件语句 if else
传递类似以下内容,但它不起作用,因为条件的长度大于1
:
if (df$ID == "A" | df$ID == "B") {
df$nat[df$value %in% c(1,2)] <- 1
df$hrv[df$value %in% c(3)] <- 1
} else {
df$nat[df$value %in% c(1)] <- 1
df$hrv[df$value %in% c(2,3)] <- 1
}
我知道我可以拆分数据集并分别进行计算,然后再将它们绑定在一起,但是否有更简单的方法,类似我上面提到的?
所以最终我想要的是这样的:
df <- data.frame(ID = c("A","A","A","B","B","B","C","C","C"),
value = c(1,2,3,1,2,3,1,2,3),
nat = c(1,1,NA,1,1,NA,1,NA,NA),
hrv = c(NA,NA,1,NA,NA,1,NA,1,1))
英文:
Opening up a new session due to too many edits.
I have a dataframe that looks like this:
df <- data.frame(ID = c("A","A","A","B","B","B","C","C","C"),
value = c(1,2,3,1,2,3,1,2,3))
And I would like to pass something like this using an if else
statement, but it does not work because the condition has length >1
:
if (df$ID =="A"| df$ID=="B"){
df$nat[df$value %in% c(1,2)] <- 1
df$hrv[df$value %in% c(3)] <- 1}
else {
df$nat[df$value %in% c(1)] <- 1
df$hrv[df$value %in% c(2,3)] <- 1}
I know I could split the dataset and do seperate calcululations and bind it together again, but is there a simpler approach, something like I suggested above?
So I would end up with something like this:
df <- data.frame(ID = c("A","A","A","B","B","B","C","C","C"),
value = c(1,2,3,1,2,3,1,2,3),
nat = c(1,1,NA,1,1,NA,1,NA,NA),
hrv = c(NA,NA,1,NA,NA,1,NA,1,1))
答案1
得分: 2
你可以使用ifelse
、if_else
或case_when
语句的变体。以下是使用dplyr
中的case_when
的示例。
library(dplyr)
df %>%
mutate(isAB = ID %in% c("A", "B"),
nat = case_when((isAB & value %in% c(1, 2))|(!isAB & value %in% 1) ~ 1),
hrv = case_when((isAB & value %in% 3)|(!isAB & value %in% c(2, 3)) ~ 1))
# ID value isAB nat hrv
#1 A 1 TRUE 1 NA
#2 A 2 TRUE 1 NA
#3 A 3 TRUE NA 1
#4 B 1 TRUE 1 NA
#5 B 2 TRUE 1 NA
#6 B 3 TRUE NA 1
#7 C 1 FALSE 1 NA
#8 C 2 FALSE NA 1
#9 C 3 FALSE NA 1
isAB
是一个临时列,用于避免多次执行ID %in% c("A", "B")
。如果不需要,你可以在最后删除它。
我们使用了OR (|
) 来组合两个条件。
英文:
You can use variations of ifelse
, if_else
or case_when
statements. Here is one using case_when
in dplyr
.
library(dplyr)
df %>%
mutate(isAB = ID %in% c("A", "B"),
nat = case_when((isAB & value %in% c(1, 2))|(!isAB & value %in% 1) ~ 1),
hrv = case_when((isAB & value %in% 3)|(!isAB & value %in% c(2, 3)) ~ 1))
# ID value isAB nat hrv
#1 A 1 TRUE 1 NA
#2 A 2 TRUE 1 NA
#3 A 3 TRUE NA 1
#4 B 1 TRUE 1 NA
#5 B 2 TRUE 1 NA
#6 B 3 TRUE NA 1
#7 C 1 FALSE 1 NA
#8 C 2 FALSE NA 1
#9 C 3 FALSE NA 1
isAB
is a temporary column created to avoid doing ID %in% c("A", "B")
multiple times. You can drop it at the end if it is not needed.
We have combined two conditions using OR (|
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论