[英]ifelse using some conditions in R
my data set is similar to this and I want to use ifelse or other functions in R. I can do it easily in Excel, but not sure how to do it it in R.我的数据集与此类似,我想在 R 中使用 ifelse 或其他函数。我可以在 Excel 中轻松完成,但不确定如何在 R 中完成。
df<-read.table(text=" Items Goods
Mug1 Cup1
Mug1 Mug2
Mug1 NA
Mug2 Mug1
Mug2 Cup2
Cup1 Mug1
Cup2 Mug2
Mug2 Cup1
Cup1 Mug2", header=TRUE)
Conditions are:条件是:
Mug1=Cup1
Mug2=Cup2
Cup1=Mug1
Cup2=Mug2
If I see the above condition, They are considered as correct.如果我看到上述情况,他们被认为是正确的。 otherwise they are incorrect.
否则他们是不正确的。 I have searched, but I could not find any solution, but it is likely I have missed some websites.
我已经搜索过,但找不到任何解决方案,但很可能我错过了一些网站。 Any help
任何帮助
I will get this table then然后我会得到这张桌子
Items Goods Out
Mug1 Cup1 Correct
Mug1 Mug2 Incorrect
Mug1 NA NA
Mug2 Mug1 Incorrect
Mug2 Cup2 Correct
Cup1 Mug1 Correct
Cup2 Mug2 Correct
Mug2 Cup1 Incorrect
Cup1 Mug2 Incorrect
In base R
, we can use a named vector, replace the values in 'Goods' by using the named vector, do a comparison ( ==
) with 'Items' to return a logical vector, which can be either used in ifelse
or convert to a position index and replace values based on that index to 'Correct', 'Incorrect'在
base R
,我们可以使用命名向量,使用命名向量替换 'Goods' 中的值,与 'Items' 进行比较 ( ==
) 以返回逻辑向量,该向量可以在ifelse
或转换到位置索引并将基于该索引的值替换为“正确”、“不正确”
nm1 <- setNames(c("Mug1", "Mug2"), c("Cup1", "Cup2"))
nm2 <- c(nm1, setNames(names(nm1), nm1))
df$Out <- with(df, c("Incorrect", "Correct")[1 + (as.character(Items) ==
nm2[as.character(Goods)])])
df
# Items Goods Out
#1 Mug1 Cup1 Correct
#2 Mug1 Mug2 Incorrect
#3 Mug1 <NA> <NA>
#4 Mug2 Mug1 Incorrect
#5 Mug2 Cup2 Correct
#6 Cup1 Mug1 Correct
#7 Cup2 Mug2 Correct
#8 Mug2 Cup1 Incorrect
#9 Cup1 Mug2 Incorrect
Or with ifelse
或者用
ifelse
with(df, unname(ifelse(as.character(Items) ==
nm2[as.character(Goods)], "Correct", "Incorrect")))
#[1] "Correct" "Incorrect" NA "Incorrect" "Correct"
#[6] "Correct" "Correct" "Incorrect" "Incorrect"
There you go:你去吧:
library(dplyr)
df<- df%>% mutate(out = ifelse(gsub("Mug","Cup",Items)==gsub("Mug","Cup",Goods),"correct","incorrect"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.