r - 根据列名的一部分将宽改成长
问题描述
有没有办法根据列名的第一部分在 R 中从宽到长重塑?我有以下数据:
id | Jan_shoulder | Jan_head | Jan_knee | Feb_shoulder | Feb_head | Feb_knee
1 | yes | no | yes | no | no | no
2 | no | no | no | yes | yes | no
我想转换它,使每一行对应一个唯一的 id 和月份,例如:
id | month | shoulder | head | knee
1 | Jan | yes | no | yes
1 | Feb | no | no | no
2 | Jan | no | no | no
2 | Feb | yes | yes | no
解决方案
使用dplyr
and tidyr
,我们可以gather
将数据转换为长格式,将separate
列名转换为不同的列,并将spread
它们转换为宽格式。
library(dplyr)
library(tidyr)
df %>%
gather(key, value, -id) %>%
separate(key, into = c("month", "part"), sep = "_") %>%
spread(part, value)
# id month head knee shoulder
#1 1 Feb no no no
#2 1 Jan no yes yes
#3 2 Feb yes no yes
#4 2 Jan no no no
推荐阅读
- javascript - 我可以更改函数内部传递的值吗?
- javascript - 如果函数处于错误情况下,我该如何停止执行?
- c# - 为什么解密后的字符串与输入的字符串不匹配?
- javascript - 如何读取同一行中的下一个值?
- c# - 如何从我的用户控件访问 label.Text
- puppet - puppetserver 作为另一个 puppetserver 的客户端
- ruby-on-rails - will_paginate 将关系误认为是数组
- r - rbind 基于列中匹配值的数据
- python-3.x - 术语“conda”未被识别为 cmdlet 的名称
- eclipse - 标题栏的Eclipse背景颜色