gpt4 book ai didi

r - 如何将一列中的因子扩展为多列——本质上是将数据集缩短一半?

转载 作者:行者123 更新时间:2023-12-02 15:56:43 24 4
gpt4 key购买 nike

如何将“strike”列分为“kick_type”和“punch_type”两列,并将“damage”列分为“kick damage”和“punch damage”?

我已经处理了 3 个小时了,但我不知道如何拆分它。请注意,我已经使用 pivot_longer 从不整洁的格式进入这个阶段,其中罢工都是列,所以我之前已经完成了其他步骤,但无法弄清楚。

可重现的代码:

trial <- data.frame(fighter=c("Saenchai","Saenchai","Saenchai","Saenchai","Buakaw","Buakaw","Buakaw","Buakaw"), 
strike=rep(c("roundhouse_kick","side_kick","lefthook_punch","uppercut_punch")),
damage=c(0.7,0.8,0.6,0.3,0.9,0.5,0.7,0.1))

它应该是这样的,但我不知道如何到达那里:

fighter   kick_type         kick_damage   punch_type      punch_damage
Saenchai roundhouse_kick 0.7 lefthook_punch 0.6
Saenchai side_kick 0.8 uppercut_punch 0.3

最佳答案

我确信有更好的方法,但这里有一种非正则表达式友好的方法:

library(tidyverse)

trial %>%
pivot_wider(names_from = "strike", values_from = "damage") %>%
pivot_longer(ends_with('kick'), names_pattern = '(.*)_kick', names_to = "kick_type", values_to = "kick_damage") %>%
pivot_longer(ends_with('punch'), names_pattern = '(.*)_punch', names_to = "punch_type", values_to = "punch_damage") %>%
group_by(fighter) %>%
filter(row_number() == 1 | row_number() == n())

# A tibble: 4 x 5
# Groups: fighter [2]
fighter kick_type kick_damage punch_type punch_damage
<chr> <chr> <dbl> <chr> <dbl>
1 Saenchai roundhouse 0.7 lefthook 0.6
2 Saenchai side 0.8 uppercut 0.3
3 Buakaw roundhouse 0.9 lefthook 0.7
4 Buakaw side 0.5 uppercut 0.1

另一种更简单的方法是使用separate:

trial %>%
separate(strike, into = c("type", "move")) %>%
group_by(fighter, move) %>%
mutate(n = row_number()) %>%
pivot_wider(c(fighter, n), names_from = move, values_from = c(type, damage))

# A tibble: 4 x 6
# Groups: fighter [2]
fighter n type_kick type_punch damage_kick damage_punch
<chr> <int> <chr> <chr> <dbl> <dbl>
1 Saenchai 1 roundhouse lefthook 0.7 0.6
2 Saenchai 2 side uppercut 0.8 0.3
3 Buakaw 1 roundhouse lefthook 0.9 0.7
4 Buakaw 2 side uppercut 0.5 0.1

关于r - 如何将一列中的因子扩展为多列——本质上是将数据集缩短一半?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71406302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com