如何将分组依据的数据框转换为另一个数据框?
How to transform a dataframe grouped by into another dataframe?
我有一个数据框
df1 <- data.frame(
"player_name" = c("bob","michel","bob","michel","bob","anna"),
"player_number" = c("1","2","1","2","1","4"),
"position" = c("1","2","2","1","2","1"),
"match" = c("match1","match1","match2","match2","match3","match3")
)
player_name player_number position match
1 bob 1 1 match1
2 michel 2 2 match1
3 bob 1 2 match2
4 michel 2 1 match2
5 bob 1 2 match3
6 anna 4 1 match3
我想把它转换成这个数据框
match position1 position2
1 match1 1 2
2 match2 2 1
3 match3 4 1
- 我最多有 12 个位置,所以我可能不想硬编码
- 我觉得我可以使用
purr
和 group_map
,但具体功能是什么?
也许你可以给我指点文档和 purr 中的正确函数,这样我可以先学习? (在回答之前:)
谢谢
您可以使用 pivot_wider
:
library(tidyverse)
pivot_wider(df1, match,
names_from = position, values_from = player_number, names_prefix = "Position")
# A tibble: 3 x 3
match Position1 Position2
<chr> <chr> <chr>
1 match1 1 2
2 match2 2 1
3 match3 4 1
在基础 R 中你会做:
reshape(df1, v.names = 'player_number',
timevar = 'position', dir='wide', idvar = 'match', drop='player_name')
match player_number.1 player_number.2
1 match1 1 2
3 match2 2 1
5 match3 4 1
与 data.table
:
library(data.table)
setDT(df1)
dcast(df1, match~position, value.var = 'player_number')
match 1 2
1: match1 1 2
2: match2 2 1
3: match3 4 1
我们可以使用 acast
来自 reshape2
library(reshape2)
acast(df1, match ~ position, value.var = 'player_number')
或使用 base R
中的 xtabs
xtabs(player_number ~ match + position, df1)
我有一个数据框
df1 <- data.frame(
"player_name" = c("bob","michel","bob","michel","bob","anna"),
"player_number" = c("1","2","1","2","1","4"),
"position" = c("1","2","2","1","2","1"),
"match" = c("match1","match1","match2","match2","match3","match3")
)
player_name player_number position match
1 bob 1 1 match1
2 michel 2 2 match1
3 bob 1 2 match2
4 michel 2 1 match2
5 bob 1 2 match3
6 anna 4 1 match3
我想把它转换成这个数据框
match position1 position2
1 match1 1 2
2 match2 2 1
3 match3 4 1
- 我最多有 12 个位置,所以我可能不想硬编码
- 我觉得我可以使用
purr
和group_map
,但具体功能是什么?
也许你可以给我指点文档和 purr 中的正确函数,这样我可以先学习? (在回答之前:)
谢谢
您可以使用 pivot_wider
:
library(tidyverse)
pivot_wider(df1, match,
names_from = position, values_from = player_number, names_prefix = "Position")
# A tibble: 3 x 3
match Position1 Position2
<chr> <chr> <chr>
1 match1 1 2
2 match2 2 1
3 match3 4 1
在基础 R 中你会做:
reshape(df1, v.names = 'player_number',
timevar = 'position', dir='wide', idvar = 'match', drop='player_name')
match player_number.1 player_number.2
1 match1 1 2
3 match2 2 1
5 match3 4 1
与 data.table
:
library(data.table)
setDT(df1)
dcast(df1, match~position, value.var = 'player_number')
match 1 2
1: match1 1 2
2: match2 2 1
3: match3 4 1
我们可以使用 acast
来自 reshape2
library(reshape2)
acast(df1, match ~ position, value.var = 'player_number')
或使用 base R
xtabs
xtabs(player_number ~ match + position, df1)