matthiash
matthiash

Reputation: 3235

In R, merge and use vector names as column names

In R I merge two vectors a and b:

a <- c(100,250)
b <- c(0,100,200)
foo <- merge(a,b,all=TRUE)

When I inspect foo, I see that the merge function has named the two columns x and y:

> foo
    x   y
1 100   0
2 250   0
3 100 100
4 250 100
5 100 200
6 250 200

Is there an elegant way of keeping the original variable names as column names in the resulting data frame? By "elegant" I mean something simpler than explicitly renaming the columns.

Upvotes: 4

Views: 1574

Answers (4)

Matias Thayer
Matias Thayer

Reputation: 621

If you prefer a complicated life, here is another option:

cross.join <- function(a, b) {
  idx <- expand.grid(seq(length=length(a)), seq(length=length(b)))
  df <- data.frame(a[idx[,1]], b[idx[,2]])
  colnames(df) <- c(deparse(substitute(a)), deparse(substitute(b)))
  return(df)
}

a <- c(100,250)
b <- c(0,100,200)
cross.join(a,b)
    a   b
1 100   0
2 250   0
3 100 100
4 250 100
5 100 200
6 250 200

Upvotes: 1

lmo
lmo

Reputation: 38500

You can also use CJ In the data.table package

library(data.table)
CJ(a=a,b=b)
     a   b
1: 100   0
2: 100 100
3: 100 200
4: 250   0
5: 250 100
6: 250 200

Note that this returns a data.table, which is similar to, but has some different behaviors from a data.frame. If you want a data.frame, you can use:

data.frame(CJ(a=a,b=b))

Upvotes: 3

TARehman
TARehman

Reputation: 6749

You can also use expand.grid() for your particular use case.

expand.grid(a = a,b = b)
    a   b
1 100   0
2 250   0
3 100 100
4 250 100
5 100 200
6 250 200

Upvotes: 8

akrun
akrun

Reputation: 886938

We can convert to a data.frame and merge

merge(as.data.frame(a), as.data.frame(b), all = TRUE)
#    a   b
#1 100   0
#2 250   0
#3 100 100
#4 250 100
#5 100 200
#6 250 200

Upvotes: 8

Related Questions