how to merge numbers from one column into the second column to create a single numeric value

advertisements

I am trying to merge the ID in column one with the numbers in column two, to create the unique ID. Here is what I start off with

1002   1    2
1002   2    0
1002   3    0
1003   1    1
1003   4    0
1003   2    1
1004   3    0

Here is what I'm trying to achieve

1002   1002.1    2
1002   1002.2    0
1002   1002.3    0
1003   1003.1    1
1003   1003.4    0
1003   1003.2    1
1004   1004.3    0

and here is my attempt

data = matrix(scan("file.txt", what = "", sep = ""), ncol = 3, byrow = T)
data = matrix(paste(data[,1], data[,2], sep = "."), ncol = 1, byrow = T)


Given the following data

df <- data.frame(
    x = c(1002, 1002, 1002, 1003, 1003, 1003, 1004),
    y = c(1, 2, 3, 1, 4, 2, 3),
    z = c(2, 0, 0, 1, 0, 1, 0)
)
print(df)

##      x y z
## 1 1002 1 2
## 2 1002 2 0
## 3 1002 3 0
## 4 1003 1 1
## 5 1003 4 0
## 6 1003 2 1
## 7 1004 3 0

You can use transform and paste0 to do the following

df <- transform(df, y = paste0(x, ".",y))
print(df)
##      x      y z
## 1 1002 1002.1 2
## 2 1002 1002.2 0
## 3 1002 1002.3 0
## 4 1003 1003.1 1
## 5 1003 1003.4 0
## 6 1003 1003.2 1
## 7 1004 1004.3 0