[英]What's wrong with my R syntax using ifelse()?
I am trying to create a column after merging two date frames that indicates 1=successful match, 2=row from data frame 1 that didn't match, 3=row from data frame 2 that didn't match.我试图在合并两个日期框架后创建一个列,指示 1 = 成功匹配,2 = 数据框 1 中不匹配的行,3 = 数据框 2 中不匹配的行。
I created a column equal to 1 in each data frame before merging so that I could analyze the merge.在合并之前,我在每个数据框中创建了一个等于 1 的列,以便我可以分析合并。
The merged data frame looks like this:合并后的数据框如下所示:
merge_s merge_p
1 NA
NA 1
1 1
Here is my code:这是我的代码:
pretest_merged$merge_result <- ifelse(pretest_merged$merge_p == 1 & pretest_merged$merge_s==1,1,
ifelse(pretest_merged$merge_p == 1 & is.na(merge_s),2,
ifelse(pretest_merged$merge_s==1 & is.na(merge_p),3,"error")))
The resulting data frame looks like this:生成的数据框如下所示:
merge_s merge_p merge_result
1 NA NA
NA 1 NA
1 1 1
When I want it to look like this:当我希望它看起来像这样时:
merge_s merge_p merge_result
1 NA 3
NA 1 2
1 1 1
I've tried getting rid of the is.na() but that doesn't work.我试过摆脱 is.na() 但这不起作用。 I've also tried using if_else() but it tells me that condition must be a logical vector and not a data frame.
我也尝试过使用 if_else() 但它告诉我条件必须是逻辑向量而不是数据框。
What am I doing wrong?我究竟做错了什么? Sorry if this question is super basic but I can't think of what else to try.
对不起,如果这个问题是超级基本的,但我想不出还有什么可以尝试的。 Thanks.
谢谢。
Without a sample dataset it's hard to help.没有样本数据集就很难提供帮助。 You should add a full reprex .
您应该添加一个完整的reprex 。
However maybe this chunk could help:然而,也许这个块可以帮助:
library(tidyverse)
df1 <- data.frame(id1 = c(1,2,3), val1 = c('blue','red','green'))
df2 <- data.frame(id2 = c(2,4,7,3), val2 = c('red','pink','grey','green'))
df_output <- merge(df1, df2, by.x = "id1", by.y = "id2", all.x = TRUE, all.y = TRUE)
df_output %>% mutate (chkcol =
case_when(
is.na(val1) == FALSE & is.na(val2) == FALSE ~ 1,
is.na(val1) == TRUE & is.na(val2) == FALSE ~ 2,
is.na(val1) == FALSE & is.na(val2) == TRUE ~ 3
)
)
df_output
id1 val1 val2 chkcol
1 1 blue <NA> 3
2 2 red red 1
3 3 green green 1
4 4 <NA> pink 2
5 7 <NA> grey 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.