Reputation: 330
I am working with R.
I have a set of data that looks like this.
principal percentage ranked
love 25 1
love 25 2
love 22 3
love 21 4
love 20 5
table 30 1
table 20 2
table 19 3
table 18 4
table 5 5
So, I need to know if the words that are in the 1 and second position in the rank are tied or not in the percentage column.
For example, I would like to have an output like this.
principal tie
love TRUE
table FALSE
Thanks.
Upvotes: 0
Views: 227
Reputation: 78927
Update: thanks to valuable comment of akrun_master! removed ifelse
library(dplyr)
# helper function to coalesce by column
coalesce_by_column <- function(df) {
return(coalesce(df[1], df[2]))
}
df %>%
group_by(principal) %>%
mutate(ties = percentage[1] == percentage[2], TRUE, FALSE) %>%
summarise(Comments = coalesce_by_column(ties))
Output:
principal Comments
<chr> <lgl>
1 love TRUE
2 table FALSE
Upvotes: 2
Reputation: 388982
You can use the following -
library(dplyr)
df %>%
group_by(principal) %>%
summarise(tie = percentage[match(1, ranked)] == percentage[match(2, ranked)])
# principal tie
# <chr> <lgl>
#1 love TRUE
#2 table FALSE
Similar alternatives will be -
#2.
df %>%
group_by(principal) %>%
summarise(tie = percentage[ranked == 1] == percentage[ranked == 2])
#3.
df %>%
arrange(principal, ranked) %>%
group_by(principal) %>%
summarise(tie = percentage[1] == percentage[2])
Upvotes: 1