1

Could anyone help me to match three or more different ranked df to have a final one containing only the rows common to all of them? I am trying match and merge functions but I can not go any further.

here is how the data may look like:

A <- data.frame(letter=LETTERS[sample(10)], x=runif(10))
B <- data.frame(letter=LETTERS[sample(10)], x=runif(10))
C <- data.frame(letter=LETTERS[sample(10)], x=runif(10))

"letter" is however the "row.names" on each df has only one column with the numerical "x", the ranked values.

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Mauro Nogueira
  • 131
  • 2
  • 13

2 Answers2

1

Create data

A <- data.frame(letter=LETTERS[sample(10)], x.A=runif(10))
B <- data.frame(letter=LETTERS[sample(10)], x.B=runif(10))
C <- data.frame(letter=LETTERS[sample(10)], x.C=runif(10))

Find intersecting letters in all the data.frames

vec.intersect <- Reduce(function(x, y) intersect(x, y), list(A[,1], B[,1], C[,1]), accumulate = FALSE)

Merge intersecting data.frames

df.intersected <- Reduce(function(x, y) merge(x, y, by = "letter"), list(A[with(A, letter %in% vec.intersect),], B, C), accumulate = FALSE)
RJ-
  • 2,919
  • 3
  • 28
  • 35
1

Thank you guys, and you @Pascal for the link which gave the solution by the function:

MyMerge       <- function(x, y){
df            <- merge(x, y, by= "row.names", all.x= F, all.y= F)
rownames(df)  <- df$Row.names
df$Row.names  <- NULL
return(df)
}
dat           <- Reduce(MyMerge, list(df1, df2, df3, df4, df5, df6))

Would be possible however to re-rank the final "dat", for instance by the sum of the values of the new rows? I am tryng stg. like that to add a column with the sum values:

 dat[,7] <- sum (dat[1:nrow (dat), ,drop=F])

but I get the sum of all values of "dat", not for each row.

Mauro Nogueira
  • 131
  • 2
  • 13