如何串联R中的数字列? [英] How to concatenate numeric columns in R?
问题描述
我在R的数据框中有三列x,y和z坐标,我想将其连接成一个xyz值,如下所示。我尝试用'collapse'=和sep =进行'粘贴',但是遇到了麻烦,我认为这与文本变量和数字变量有关。
I have three columns of x, y, and z coordinates in a dataframe in R that I would like to concatenate into one xyz value, like below. I have tried 'paste' with 'collapse'="" and sep="" but am having trouble, I think it's something to do with text vs. numeric variables.
I have:
x y z
1 2 3
2 3 2
3 1 4
4 2 1
I want:
x y z xyz
1 2 3 123
2 3 2 232
3 1 4 314
4 2 1 421
在R中必须有一些非常简单的方法,但是我一直在使用Google谷歌搜索技术-在过去的几天里,没有任何东西引起我的注意。我需要的是xyz列要唯一,因此我可以运行固定效果回归(x范围为1:4,y范围为1:4和z 1:10),因此我有160种可能的组合。目前,我在x,y和z值上使用不同的指数,然后将它们相乘以获得唯一值-当然,有更好的方法!谢谢
There has to be some extremely easy/simple way to do this in R but I have been Googling and looking through Stack Overflow off-and-on for the past couple days and nothing has come to my attention. All I need is the xyz column to be unique so I can run fixed-effects regressions, (x ranges from 1:4, y from 1:4 and z 1:10) so I have 160 possible combinations. Currently I am using different exponents on the x, y, and z values and then multiplying them to get unique values--surely there's a better way! Thanks
推荐答案
例如:
transform(df,xyz=paste0(x,y,z))
x y z xyz
1 1 2 3 123
2 2 3 2 232
3 3 1 4 314
4 4 2 1 421
或使用互动
:
transform(df,xyz=interaction(x,y,z,sep=''))
x y z xyz
1 1 2 3 123
2 2 3 2 232
3 3 1 4 314
4 4 2 1 421
`
这篇关于如何串联R中的数字列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!