0

I know that it is quite a simple question but I'm still quite new to R.

If I have two tables like this

id = c(1,2,3,4,5,6)
cost = c(11,22,33,44,55,66)
name =c("aa","bb","cc","dd","ee","ff")

tableone = cbind (id, cost)
tabletwo = cbind(name,id)

how can I add the correct names (as in tabletwo) to tableone with the costs? In reality table1 is much more complex with multiple duplications etc.

  • Give a fuller example of the actual data because it sounds like the solution here is `cbind(name,id,cost)` but you imply that it's more complex than that. – Thomas May 08 '13 at 13:18

1 Answers1

1

Here's a way using the data.table package:

Load the package:

library(data.table)

Load your vectors as you had them defined:

id <- c(1,2,3,4,5,6)
cost <- c(11,22,33,44,55,66)
name <- c("aa","bb","cc","dd","ee","ff")

Turn the vectors into single column data tables:

id.dt<-data.table(id)
setnames(id.dt,"id")

cost.dt<-data.table(cost)
setnames(cost.dt,"cost")

name.dt<-data.table(name)
setnames(name.dt,"name")

Combine columns, set a key (this might be unneeded for this example, but I included it just to show:

tableone.dt<-cbind(id.dt,cost.dt)
setkey(tableone.dt,id)
tabletwo.dt<-cbind(name.dt,id.dt)
setkey(tabletwo.dt,id)

Merge the tables:

merge(tableone.dt,tabletwo.dt)

Of course this is a round-about way of doing it. If it suits your needs you can easily simplify the process. For example:

simple.table <- data.table("id"=c(1,2,3,4,5,6),"cost"=c(11,22,33,44,55,66),"name"=name <- c("aa","bb","cc","dd","ee","ff"))

or Thomas's comment will work. Also, do see the link commented by flodel.

Docuemada
  • 1,703
  • 2
  • 25
  • 44