Reputation: 53
Sorry that i didn't specify: V1 and V2 are factor values. When I
sign(as.numeric(df$V1)) == sign(as.numeric(df$V2))
Every case returns true.
Check if every row in two columns has the same sign. Return false if one is 0, but true when both are; an example is as follows:
V1 V2
-1 2.3
3.6 2
-2 -4
0 4
0 0
V1 V2 comparison
-1 2.3 false
3.6 2 true
-2 -4 true
0 4 false
0 0 true
I came up with this which always returns true:
output.df$comparison = (((as.numeric(output.df$V1) > 0) & (as.numeric(output.df$V2) > 0)) | ((as.numeric(output.df$V1) < 0) & (as.numeric(output.df$V2) < 0)))
Upvotes: 1
Views: 1047
Reputation: 158
dplyr way:
df <- df %>% mutate(comparison = (sign(V1) == sign(V2))
Upvotes: 0
Reputation: 39858
Another base R
idea could be:
apply(df, 1, function(x) sd(sign(x))) == 0
[1] FALSE TRUE TRUE FALSE TRUE
Upvotes: 1
Reputation: 388982
You can compare their sign
which will handle case for 0 as well.
df$comparison <- sign(df$V1) == sign(df$V2)
df
# V1 V2 comparison
#1 -1.0 2.3 FALSE
#2 3.6 2.0 TRUE
#3 -2.0 -4.0 TRUE
#4 0.0 4.0 FALSE
#5 0.0 0.0 TRUE
data
df <- structure(list(V1 = c(-1, 3.6, -2, 0, 0), V2 = c(2.3, 2, -4,
4, 0)), class = "data.frame", row.names = c(NA, -5L))
Upvotes: 4