Good I am trying to make a filter in R but the result is not as expected
x1 = c("PIB","PIB","PIB","PIB","PIB")
x2 = c("IBR","IBR","IBR","IBR","IBR")
coef_x1 = c(0.001,0.004,0.002,-0.099,-0.88)
coef_x2 = c(0.12,0.15,-0.99,-0.77,0.45)
Signo_x1 = c(" "," "," "," "," ")
Signo_x2 = c(" "," "," "," "," ")
Table = data.frame(x1,x2,coef_x1,coef_x2,Signo_x1,Signo_x2)
that's the table I have
x1 x2 coef_x1 coef_x2 Signo_x1 Signo_x2
1 PIB IBR 0.001 0.12
2 PIB IBR 0.004 0.15
3 PIB IBR 0.002 -0.99
4 PIB IBR -0.099 -0.77
5 PIB IBR -0.880 0.45
I need to perform a filter as follows
x1 x2 coef_x1 coef_x2 Signo_x1 Signo_x2
1 PIB IBR 0.001 0.12
2 PIB IBR 0.004 0.15
3 PIB IBR 0.002 -0.99
for the filter I am executing the following code:
updated here
Table = ifelse(Table$Signo_x1 == " ",Table %>% dplyr::filter(Table$coef_x1 >= 0),Table %>% dplyr::filter(Table$coef_x1 <= 0))
[[1]]
[1] "PIB" "PIB" "PIB"
[[2]]
[1] "IBR" "IBR" "IBR"
[[3]]
[1] 0.001 0.004 0.002
[[4]]
[1] 0.12 0.15 -0.99
[[5]]
[1] " " " " " "
anyone has the knowledge of how to convert it back as a dataframe or if the code i am using is not correct how could i fix it?
CodePudding user response:
We need to use &
to create the expression
library(dplyr)
Table %>%
filter(Signo_x1 == " " & coef_x1 >= 0)
-output
x1 x2 coef_x1 coef_x2 Signo_x1 Signo_x2
1 PIB IBR 0.001 0.12
2 PIB IBR 0.004 0.15
3 PIB IBR 0.002 -0.99
Based on the comments, we may need if/else
Table %>%
filter(if(any(Signo_x1 == " " & coef_x1 >= 0))
Signo_x1 == " " & coef_x1 >= 0 else coef_x1 <=0)
x1 x2 coef_x1 coef_x2 Signo_x1 Signo_x2
1 PIB IBR 0.001 0.12
2 PIB IBR 0.004 0.15
3 PIB IBR 0.002 -0.99
Or use subset
from base R
subset(Table, Signo_x1 == " " & coef_x1 >= 0)