给定一个包含 A 列的 R 数据框,如何创建两个包含 A 的所有有序组合的新列
我有一个 data.frame,其中有一个 id 列(下面的 x)和许多变量(下面的 y1,y2)。
x y1 y2
1 1 43 55
2 2 51 53
[...]
我想从中生成一个数据框,其中前两列涵盖 x 的每个有序组合(除非它们相等)以及与顺序相关的每个变量的列。数据帧标题和前两行看起来像这样(手动完成,请原谅错误):
xi xj y1i y1j y2i y2j
1 2 43 51 55 53
2 1 51 43 53 55
[...]
因此,每一行将包含源和目标(i 和 j),然后包含每个源和目标处的 y1 值。
我正在慢慢学习 R 数据操作,但这一个难倒了我。感谢一行万能的答案,以及更具可读性的说教答案。
I have a data.frame with one id column (x below), and a number of variables (y1,y2 below).
x y1 y2
1 1 43 55
2 2 51 53
[...]
What I would like to generate from this is a dataframe where the first two columns cover every ordered combination of x (except where they are equal) along with columns for each variable related to the order. The data frame header and first two rows would look like this (did this by hand, excuse errors):
xi xj y1i y1j y2i y2j
1 2 43 51 55 53
2 1 51 43 53 55
[...]
So each row would container a source and destination (i and j) and then values for y1 at each source and destination.
I'm slowly learning R data manipulation, but this one is stumping me. Kudos for the one line does-it-all answer, as well as a more readable didactic answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(可能除了顺序)
这可以产生
第一行和第五行与您的示例匹配的位置
。如果您将
firstdf
视为给定并坚持一行,那么您可以将其变成但我真的不明白这一点
This works (apart perhaps from order)
to produce
where the first and fifth rows match your example.
If you take
firstdf
as given and insist on one line then you can turn this intobut I don't really see the point
两行是我能做的最好的事情,并且仍然保持合理:(编辑:参见单行答案的底部。)
创建一些数据:
代码:
结果:
编辑
可以通过使用匿名函数将其变成单行
Two lines is the best I can do and still keep it sensible: (Edit: see bottom of answer for one-liner.)
Create some data:
The code:
The results:
EDIT
This can be turned into a one-liner by making use of anonymous functions:
我不确定您总体上到底想要什么,但据我了解,这可能接近您想要的:
如果您提供更详细的信息,可能您可以获得更好的答案。
I'm not sure what you exactly want in general, but as far as my understanding, this may be close to what you want:
If you provide information in more detail, probably you can get better answers.
好吧,它与单行相去甚远(我有点怀疑这是可能的),但这里有一种“天真的”方法:
我没有命名这些列,但事后很容易完成。
不是很优雅,但也许可以帮助你开始......
Well, it's nowhere close to a one-liner (which I kind of doubt is possible) but here's a 'naive' approach:
I didn't name the columns, but that's easily done after the fact.
Not very elegant, but maybe something to get you started...