我有两个数据帧包含相关数据。这与NFL有关。一个DF有按周球员的名字和接收目标(玩家DF):R:如何从两个其他数据帧创建一个新的数据帧
Player Tm Position 1 2 3 4 5 6
1 A.J. Green CIN WR 13 8 11 12 8 10
2 Aaron Burbridge SFO WR 0 1 0 2 0 0
3 Aaron Ripkowski GNB RB 0 0 0 0 0 1
4 Adam Humphries TAM WR 5 8 12 4 2 0
5 Adam Thielen MIN WR 5 5 4 3 8 0
6 Adrian Peterson MIN RB 2 3 0 0 0 0
其他数据帧recieving通过团队总结目标,每星期(团队DF):
Tm `1` `2` `3` `4` `5` `6`
<fctr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 ARI 37 35 50 45 26 35
2 ATL 38 34 30 37 28 41
3 BAL 32 45 40 51 47 48
4 BUF 22 30 20 33 20 26
5 CAR 31 39 36 47 28 46
6 CHI 28 29 45 36 41 49
7 CIN 30 54 28 31 39 31
8 CLE 26 33 38 38 35 42
9 DAL 43 30 24 32 24 27
10 DEN 26 32 35 31 34 47
# ... with 22 more rows
我是什么试图做的是按星期创建另一个包含玩家目标百分比的数据框。所以我需要匹配球员df中的“Tm”列和周列标题(1-6)中的球队。
我已经找到了如何通过将它们合并,然后创建新行要做到这一点,但我添加更多的数据(周)我需要编写更多的代码:
a <- merge(playertgt, teamtgt, by="Tm") #merges the two
a$Wk1 <- a$`1.x`/a$`1.y`
a$Wk2 <- a$`2.x`/a$`2.y`
a$Wk3 <- a$`3.x`/a$`3.y`
所以我要寻找是一个很好的方法来做到这一点,将自动更新,并不需要创建一个df与我不需要的一堆列,并将更新与新周,因为我将它们添加到我的源数据。
如果在其他地方回答这个问题,我很抱歉,但我一直在寻找一种很好的方法来做到这一点,我找不到它。在此先感谢您的帮助!很显然,我只是在完成合并后选择列使用dplyr
为ends_with
方便
library(dplyr)
## Do a left outer join to match each player with total team targets
a <- left_join(playertgt,teamtgt, by="Tm")
## Compute percentage over all weeks selecting player columns ending with ".x"
## and dividing by corresponding team columns ending with ".y"
tgt.pct <- select(a,ends_with(".x"))/select(a,ends_with(".y"))
## set the column names to week + number
colnames(tgt.pct) <- paste0("week",seq_len(ncol(teamtgt)-1))
## construct the output data frame adding back the player and team columns
tgt.pct <- data.frame(Player=playertgt$Player,Tm=playertgt$Tm,tgt.pct)
: