如何在另一个向量上使用递归求值条件向量

时间:2019-06-17 13:08:57

标签: r if-statement

在两个不同数据帧的行和列中是否存在条件时进行应用。

数据

df1<- data.frame(X1=10,
                 X2=12,
                 X3= 8,
                 X4=4,
                 X5=6)

df2<-data.frame(Class = c("class_1", "class_2","class_3", "class_4", "class_5", "class_6",
                "class_7", "class_8", "class_9", "class_10"),
                MARKS = c(8,6,9,10,11,8,5,4,7,5))

输出

class 1     Y       Y   FALSE   FALSE   FALSE
class 2     Y       Y   Y       FALSE   FALSE
class 3     Y       Y   FALSE   FALSE   FALSE
class 4     FALSE   Y   FALSE   FALSE   FALSE
class 5     FALSE   Y   FALSE   FALSE   FALSE
class 6     Y       Y   FALSE   FALSE   FALSE
class 7     Y       Y   Y       FALSE   Y
class 8     Y       Y   Y       FALSE   Y
class 9     Y       Y   Y       FALSE   FALSE
class 10    Y       Y   Y       FALSE   Y

formula: =IF($A$2>$I2,"Y")
FOR CLASS 1 - I2 WILL BE CONSTANT 
例如:其中A2 = df1的10,I2 = df2的8。如果10> 8,则打印Y,否则条件失败并打印FALSE。

FOR CLASS 2 - I3 WILL BE CONSTANT 
FORMULA =IF($A$2>$I3,"Y")

Similary,其中B2 = DF1为12,I3 = df2为6,因此,如果12> 6打印Y,否则条件失败并打印FALSE。

2 个答案:

答案 0 :(得分:2)

您可以按以下方式使用ifelse()进行递归操作:

> Res<-apply(df1,2,function(x){ifelse((x<=df2$MARKS), "FALSE", "Y")})
> rownames(Res)<- df2$Class      
> Res
         X1      X2  X3      X4      X5     
class_1  "Y"     "Y" "FALSE" "FALSE" "FALSE"
class_2  "Y"     "Y" "Y"     "FALSE" "FALSE"
class_3  "Y"     "Y" "FALSE" "FALSE" "FALSE"
class_4  "FALSE" "Y" "FALSE" "FALSE" "FALSE"
class_5  "FALSE" "Y" "FALSE" "FALSE" "FALSE"
class_6  "Y"     "Y" "FALSE" "FALSE" "FALSE"
class_7  "Y"     "Y" "Y"     "FALSE" "Y"    
class_8  "Y"     "Y" "Y"     "FALSE" "Y"    
class_9  "Y"     "Y" "Y"     "FALSE" "FALSE"
class_10 "Y"     "Y" "Y"     "FALSE" "Y"    

答案 1 :(得分:0)

您可以使用dplyrbase R组合键。首先,我将df1设为与df2相同的长度,然后按列将它们绑定在一起。然后,将公式应用于名称中带有字母X的每一列:

library(dplyr)

df2 %>% 
  bind_cols(df1[rep(seq_len(nrow(df1)), each=nrow(df2)),]) %>% 
  mutate_at(vars(contains("X")), ~if_else(. <= MARKS, "FALSE", "Y"))

结果:

      Class MARKS    X1 X2    X3    X4    X5
1   class_1     8     Y  Y FALSE FALSE FALSE
2   class_2     6     Y  Y     Y FALSE FALSE
3   class_3     9     Y  Y FALSE FALSE FALSE
4   class_4    10 FALSE  Y FALSE FALSE FALSE
5   class_5    11 FALSE  Y FALSE FALSE FALSE
6   class_6     8     Y  Y FALSE FALSE FALSE
7   class_7     5     Y  Y     Y FALSE     Y
8   class_8     4     Y  Y     Y FALSE     Y
9   class_9     7     Y  Y     Y FALSE FALSE
10 class_10     5     Y  Y     Y FALSE     Y