作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何将“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/
我了解了 NodeJS 的非阻塞特性,以及 I/O 操作如何实现非阻塞。我创建了一个简单的测试来证明这一点 var request = require('request'); var http = r
我是一名优秀的程序员,十分优秀!