Pregunta

I have a list of dataframes df_list that looks like this:

 head(df_list[[1]])
       score    name  rank
 921   9718     aba   921
 346   11387    aca   346

head(df_list[[2]]
       score    name  rank
 1080  9023     aba   1080
 156   12276    aca   156

and I would like to merge them together on the name, so that I get something like

       score.1  rank.1   score.2   rank.2
 aba   9718     921      9023      1080 
 aca   11387    346      12276     156  

I tried using do.call and cbind like

tmp <- do.call("cbind", df_list)

however, this gives me

head(tmp)
      score    name  rank   score   name   rank
921   9718     aba   921    9718    aba    1080 
346   11387    aca   346    11387   aca    156 

and when I try to get the rankings with tmp[tmp$rank] I can only get the first column named rank.

¿Fue útil?

Solución

Using merge

 merge(dt1,dt2,by='name', suffixes = c(".1",".2"))
  name score.1 rank.1 score.2 rank.2
1  aba    9718    921    9023   1080
2  aca   11387    346   12276    156

If you have more than 2 elements:

ll <- list(dt1,dt2)

Merge <- 
  function(x,y)
merge(x,y,by='name', suffixes = c(".1",".2"))
Reduce(Merge,ll)
 name score.1 rank.1 score.2 rank.2
1  aba    9718    921    9023   1080
2  aca   11387    346   12276    156

Otros consejos

cbind() is doing exactly what it is meant to do, placing the columns side-by-side. If you want to merge them, you need to use the merge() function.

If your data always has the same observations (in the same order) then cbind would be appropriate. In that case you just remove the name column from all data.frames except the first and rename the other columns tagging them with a counter.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top