假设我有此数据框:
df <- data.frame(
party = c("A", "A", "B", "A", "B"),
votes = c(100, 99, 98, 97, 96),
elected = c(1, 1, 1, 0, 0, 0)
)
party votes elected
1 A 100 1
2 A 99 1
3 B 98 1
4 A 97 0
5 B 96 0
我想计算一个新变量,它是挑战者候选人的票数,这是来自另一方的第一个非当选候选人的票数。结果将是:
party votes elected votes_challenge
1 A 100 1 96
2 A 99 1 96
3 B 98 1 97
4 A 97 0 NA
5 B 96 0 NA
我已经尝试过first()
和lag()
的条件,但现在没有which()
的运气。希望得到帮助。
这是使用fuzzyjoin
-程序包的一个选项
library(fuzzyjoin)
library(tidyverse)
fuzzy_left_join(df, df %>%
arrange(party, elected, desc(votes)) %>%
group_by(party) %>% slice(1) ,
by = c("party", "elected"), match_fun = list(`!=`, `>`)) %>%
select(ends_with("x"), votes.y)
party.x votes.x elected.x votes.y
1 A 100 1 96
2 A 99 1 96
3 B 98 1 97
4 A 97 0 NA
5 B 96 0 NA
也许这对您有用
您可以尝试使用功能
library(dplyr)
get_opposite_votes <- function(df, group) {
df %>% filter(party != group & elected == 0) %>% slice(1L) %>% pull(votes)
}
df %>%
group_by(party) %>%
mutate(new = get_opposite_votes(., first(party))) %>%
ungroup() %>%
#If needed to have NA values where elected = 0
mutate(new = replace(new, elected == 0, NA))
# party votes elected new
# <fct> <dbl> <dbl> <dbl>
#1 A 100 1 96
#2 A 99 1 96
#3 B 98 1 97
#4 A 97 0 NA
#5 B 96 0 NA