How to concatenate numeric columns in R?

I have three columns of x, y, and z coordinates in a data frame in R that I would like to combine into a single xyz value, as shown below. I tried to "insert" with "collapse" = "and sep =" ", but I have problems, I think it has something to do with text and 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

There should be a very simple / easy way to do this in R, but I have been Googling and browsing Qaru for the last two days and nothing has caught my attention. All I need is an xyz column to be unique, so I can trigger regressions with fixed effects, (x varies from 1: 4, y from 1: 4 and z 1:10), so I have 160 possible combinations . Currently, I use different metrics for x, y, and z, and then multiplying them by getting unique values ​​is undoubtedly the best way! Thanks

+4
source share
2 answers

For instance:

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

Or using interaction:

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

`

+6
source
df$NewCol <- do.call(paste, c(df[c("x", "y", "z")], sep = ""))
+4
source

Source: https://habr.com/ru/post/1544779/


All Articles