簡體   English   中英

如何將列名與 R 中同一 dataframe 中的其他列中的數據匹配?

[英]How can I match column names to data in other columns in the same dataframe in R?

我有一個包含體育數據的數據集。 每一行對於每支球隊來說都是一個不同的賽季(所以如果有 5 個賽季,那么一支球隊會有 5 個賽季)。 如果他們晉級錦標賽,我還有一個專欄,上面寫着“是”或“否”。 最后,我有每個團隊的列(在同一張表中),它顯示了針對該團隊的記錄。 如何將這些列的名稱(團隊名稱)與表中前面的相同團隊名稱相匹配,以便我可以知道列團隊是否晉級了錦標賽?

season advanced team  tm   tm1   tm2   tm3   tm4   tm5  
2015     Yes    team1 tm1  NA    1-3   2-0   4-1   3-2    
2015     Yes    team2 tm2  3-1   NA    2-1   1-1   2-0    
2015      No    team3 tm3  0-2   1-2   NA    1-3   2-1    
2015      No    team4 tm3  1-4   1-1   3-1   NA    2-2    
2015      No    team5 tm5  2-3   0-2   1-2   2-2   NA     

我希望能夠總結每支球隊對非進步對手的勝利次數。 例如,會有一個額外的列:

season advanced team  tm  tm1   tm2   tm3   tm4   tm5  wins_V_non
2015     Yes    team1 tm1  NA    1-3   2-0   4-1   3-2    9
2015     Yes    team2 tm2  3-1   NA    2-1   1-1   2-0    5
2015      No    team3 tm3  0-2   1-2   NA    1-3   2-1    3
2015      No    team4 tm3  1-4   1-1   3-1   NA    2-2    5
2015      No    team5 tm5  2-3   0-2   1-2   2-2   NA     3

我不確定如何匹配沒有進入各自專欄的團隊來制作這個新的“wins_V_non”專欄。

謝謝!

loss <- df$team[df$advanced=='No']

df %>%
  left_join(pivot_longer(.,-c(season, advanced, team)) %>%
  separate(value, c('fr', 'against'), convert = TRUE) %>%
  group_by(season, team) %>%
  summarise(wins = sum(fr[name %in% loss], na.rm = TRUE),.groups = 'drop'))

  season advanced  team team1 team2 team3 team4 team5 wins
1   2015      Yes team1  <NA>   1-3   2-0   4-1   3-2    9
2   2015      Yes team2   3-1  <NA>   2-1   1-1   2-0    5
3   2015       No team3   0-2   1-2  <NA>   1-3   2-1    3
4   2015       No team4   1-4   1-1   3-1  <NA>   2-2    5
5   2015       No team5   2-3   0-2   1-2   2-2  <NA>    3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM