[英]Intersect compare vectors in r
I have a dataframe with 4 colums here is the structure. 我有一个带有4列的数据框,这里是结构。
I would like to create a new vector (valuetofind) with the value of 1 if all my rows have the number 1 and -1 if all my rows have the number -1. 我想创建一个新的向量(valuetofind),如果我所有行的数字都为1,则返回-1,如果我所有行的数字都为-1,则返回-1。
Otherwhise just fill with NA. 其他只是用NA填充。
str(results)
'data.frame': 435 obs. of 4 variables:
$ model.knn: Factor w/ 2 levels "-1","1": 2 2 2 2 2 2 2 1 2 2 ...
$ p.arbre : Factor w/ 2 levels "-1","1": 2 2 1 1 2 2 2 1 2 2 ...
$ p.svm : Factor w/ 2 levels "-1","1": 2 2 2 2 2 2 2 2 2 2 ...
$ p.rf : Factor w/ 2 levels "-1","1": 2 2 2 1 2 2 2 1 2 2 ...
model.knn p.arbre p.svm p.rf Valuetofind
1 1 1 1 1
-1 -1 1 1 NA
-1 -1 -1 -1 -1
I have been trying many things but I am blocked 我已经尝试了很多事情,但被阻止了
I tried to convert to numeric, the facor in my dataframe. 我试图将其转换为数值,即数据框中的外观。 It gave me values of 2 and 1 instread of my -1 and 1.
它使我的-1和1的值分别为2和1。
Use nested ifelse()
and rowSums()
for base
solution. 将嵌套的
ifelse()
和rowSums()
用于base
解决方案。
results <- data.frame(model.knn = c(1, -1, -1), p.arbre = c(1, -1, -1), p.svm = c(1, 1, -1), p.rf = c(1, 1, -1))
results["Valuetofind"] <- ifelse(rowSums(results) == ncol(results), 1,
ifelse(rowSums(results) == -ncol(results), -1, NA))
results
model.knn p.arbre p.svm p.rf Valuetofind
1 1 1 1 1 1
2 -1 -1 1 1 NA
3 -1 -1 -1 -1 -1
You can try dplyr::case_when()
if there are multiple ifelse()
nesting. 如果有多个
ifelse()
嵌套,则可以尝试dplyr::case_when()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.