每个n列都宽至长时间
假设我有一个dataframe:
dw <- read.table(header=T, text='
ID q1 q2 q3 q4 q5 ...q10
A 10 6 50 10 bA
B 12 5 70 11 bB
C 20 7 20 8 bC
D 22 8 22 9 bD
')
我想在'id'
之后移动每2列到新行,因此看起来像:
ID q1 q2
A 10 6
B 12 5
C 20 7
D 22 8
A 50 10
B 70 11
C 20 8
D 22 9
....
pivot_longer
似乎可以移动每个列而不是多个列列?
Suppose I have a dataframe:
dw <- read.table(header=T, text='
ID q1 q2 q3 q4 q5 ...q10
A 10 6 50 10 bA
B 12 5 70 11 bB
C 20 7 20 8 bC
D 22 8 22 9 bD
')
I would like to move every 2 columns after 'ID'
to new rows so it looks like:
ID q1 q2
A 10 6
B 12 5
C 20 7
D 22 8
A 50 10
B 70 11
C 20 8
D 22 9
....
pivot_longer
seems to move every single column instead of multiple columns?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
似乎您不关心列名(
id
),而它们都是同一类。为此,我们可以手动“旋转”,而无需pivot_lower
的保障或功能,但也没有要求。第一步是确保
class
不会成为问题。因为您在那里有一些字符串,所以我们需要将全部转换为targue
:之后,我们可以手动提取每两个(non-
id
)列,并与id :
这可以轻松地与几种方法结合在一起,选择一种:
数据之一
It seems that you are not concerned with the column names (other than
ID
), and that they are all the same class. For this, we can "pivot" manually, without the safeguards or power ofpivot_lower
perhaps, but without the requirements as well.The first step is to make sure that
class
won't be an issue; because you have some strings in there, we need to convert all tocharacter
:After that, we can manually extract every two (non-
ID
) columns and combine withID
:This can be easily combined with several methods, choose one of:
Data
另一个选项:
使用数据:
或更一般:
Another option:
With data:
Or more generally:
Melt(...)
data.table
的方法允许列表融化列。使用dw
来自 @r2evans答案:Melt(...)
引入列actible
,该可以跟踪原始列的位置宽数据集。您似乎不在乎这一点,因此已将其删除。如果确实有不同的类(整数,字符)熔体(...)
将通过警告来处理这一点。The
melt(...)
method fordata.table
allows for melting groups of columns. Usingdw
from @r2evans answer:melt(...)
introduces a columnvariable
which keeps track of the location of the original columns in the wide dataset. You don't seem to care about that so it's removed. If there are indeed different classes (integer, character)melt(...)
will take care of that with a warning.