0

这是一般使用Microsoft Excel 解决的一类问题。由于我不熟悉 VBA 和宏,我需要借助R.

数据框如下所示。

df <- data.frame(player_no = c(1,2,3,4,5,6), player = c("Ram", "Shyam", "Jordan", "Chris", "Salim", "Salman"), sold_to = c("Team_1", "Team_2", "Team_3", "Team_2", "Team_3", "Team_1"))

现在我希望创建一个新的数据框,其中 player_no 和 player 的值会自动填充到各自的团队中。

预期的图形表示如下所示:-

在此处输入图像描述

预期输出如下

#          Team 1                    Team 2              Team 3
# Sno player_no  player  Sno  player_no  player  Sno player_no player
# 1    1          Ram     1     2         Shyam   1   3         Jordan
# 2    6          Salman  2     4         Chris   2   5         Salim

一旦达到预期的输出,是否可以将输出传输回一个writexl模仿问题中提到的图形表示的 excel 文件(使用包)?

4

1 回答 1

1

你可以使用dplyrand tidyr

df %>%
  pivot_wider(names_from="sold_to", 
              names_glue="{sold_to}_{.value}", 
              values_from=c("player_no", "player"), 
              values_fn=list
              ) %>%
  unnest(everything()) %>%
  select(Team_1_player_no, Team_1_player, 
         Team_2_player_no, Team_2_player, 
         Team_3_player_no, Team_3_player)

它不完全返回您想要的输出,但它非常相似:

# A tibble: 2 x 6
  Team_1_player_no Team_1_player Team_2_player_no Team_2_player Team_3_player_no Team_3_player
             <dbl> <fct>                    <dbl> <fct>                    <dbl> <fct>        
1                1 Ram                          2 Shyam                        3 Jordan       
2                6 Salman                       4 Chris                        5 Salim  
于 2020-06-29T10:57:28.027 回答