Canovice
Canovice

Reputation: 10173

R - automatically rename column names to name.x name.y with cbind

Question is fairly straightforward. Let's say I have two dataframes:

> dput(x)
structure(list(a1 = 1:3, b1 = c("a", "b", "c")), .Names = c("a1", "b1"), row.names = c(NA, -3L), class = "data.frame")
> dput(z)
structure(list(a1 = 4:6, b2 = c("d", "e", "f")), .Names = c("a1", "b2"), row.names = c(NA, -3L), class = "data.frame")

head(x)
  a1 b1
1  1  a
2  2  b
3  3  c

head(z)
  a1 b2
1  4  d
2  5  e
3  6  f

when i cbind these dataframes, I get this:

cbind(x,z)
  a1 b1 a1 b2
1  1  a  4  d
2  2  b  5  e
3  3  c  6  f

but I want this:

cbind(x,z)
  a1.x b1 a1.y b2
1    1  a    4  d
2    2  b    5  e
3    3  c    6  f

where column names aren't duplicated, but rather matching column names get a .x and .y. this is similar to the behavior of merge I believe. Note I don't necessarily need to use cbind(), just (preferably) a one-liner function that would get this done.

Thanks!

Upvotes: 1

Views: 1702

Answers (3)

R.Y
R.Y

Reputation: 21

After you combine the two dataframes using cbind function, you can make unique column names of the new dataframe.

y <- cbind(x,z)
colnames(y) <- make.names(colnames(y), unique = TRUE)

If you print y the you will get

a1 b1 a1.1 b2

1 1 a 4 d

2 2 b 5 e

3 3 c 6 f

Upvotes: 0

akrun
akrun

Reputation: 887168

We can use merge with row.names

merge(x, z, by = "row.names")[-1]
#   a1.x b1 a1.y b2
#1    1  a    4  d
#2    2  b    5  e
#3    3  c    6  f

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

We can use merge here with by = 0

merge(x, z, by = 0)

#  Row.names a1.x b1 a1.y b2
#1         1    1  a    4  d
#2         2    2  b    5  e
#3         3    3  c    6  f

The document in ?merge specifies

Columns to merge on can be specified by name, number or by a logical vector: the name "row.names" or the number 0 specifies the row names.

So here we are merging the two dataframes by their rownames

rownames(x)
#[1] "1" "2" "3"
rownames(z)
#[1] "1" "2" "3"

Upvotes: 5

Related Questions