我的数据格式为:
df_original <-
tibble(
unique_id = c(1, 1, 2, 2),
player_name = c('A', 'B', 'C', 'D'),
player_points = c(5, 7, 3, 4)
)
unique_id player_name player_points
<dbl> <chr> <dbl>
1 1 A 5
2 1 B 7
3 2 C 3
4 2 D 4
我想对其进行转换,以使结果数据帧如下所示:
unique_id player_name player_points_scored player_points_allowed
<dbl> <chr> <dbl> <dbl>
1 1 A 5 7
2 1 B 7 5
3 2 C 3 4
4 2 D 4 3
基本上,我想按unique_id
“分组”,然后对其进行转换。我假设pivot_wider
中的tidyr
函数是解决方案,但是语法对我来说并不直观,我无法弄清楚如何解决它。
答案 0 :(得分:3)
我们可以使用rev
将player_points
反转unique_id
。
library(dplyr)
df_original %>%
group_by(unique_id) %>%
mutate(player_points_allowed = rev(player_points))
# unique_id player_name player_points player_points_allowed
# <dbl> <chr> <dbl> <dbl>
#1 1 A 5 7
#2 1 B 7 5
#3 2 C 3 4
#4 2 D 4 3
同样可以在基本R中实现
df_original$player_points_allowed <- with(df_original, ave(player_points,
unique_id, FUN = rev))
和data.table
。
library(data.table)
setDT(df_original)[, player_points_allowed := rev(player_points), unique_id]
答案 1 :(得分:0)
我们可以按索引反转
library(dplyr)
df_original %>%
group_by(unique_id) %>%
mutate(player_points_allowed = player_points[n():1])
或与data.table
library(data.table)
setDT(df_original)[, player_points_allowed := player_points[.N:1], unique_id]