Merge dataframes, different lengths
You could add a join variable to dat2 then using merge:
dat2$variable <- rownames(dat2)
merge(dat1, dat2)
variable ID value concreteness familiarity typicality
1 amoeba 1 0 3.60 1.30 1.71
2 amoeba 2 0 3.60 1.30 1.71
3 amoeba 3 NA 3.60 1.30 1.71
4 bacterium 1 0 3.82 3.48 2.13
5 bacterium 2 0 3.82 3.48 2.13
6 bacterium 3 0 3.82 3.48 2.13
7 leech 1 1 5.71 1.83 4.50
8 leech 2 1 5.71 1.83 4.50
9 leech 3 0 5.71 1.83 4.50
Try this:
merge(dat1, dat2, by.x = 2, by.y = 0, all.x = TRUE)
This assumes that if there are any rows in dat1
that are unmatched then the dat2
columns in the result should be filled with NA
and if there are unmatched values in dat2
then they are disregarded. For example:
dat2a <- dat2
rownames(2a)[3] <- "elephant"
# the above still works:
merge(dat1, dat2a, by.x = 2, by.y = 0, all.x = TRUE)
The above is known as a left join in SQL and can be done like this in sqldf (ignore the warning):
library(sqldf)
sqldf("select *
from dat1 left join dat2
on dat1.variable = dat2.row_names",
row.names = TRUE)
Nothing wrong with @agstudy's answer, but you can do it without actually modifying dat2 by creating an anonymous temporary. Adding X is similar:
> merge(cbind(dat1, X=rownames(dat1)), cbind(dat2, variable=rownames(dat2)))
variable ID value X concreteness familiarity typicality
1 amoeba 1 0 1 3.60 1.30 1.71
2 amoeba 2 0 2 3.60 1.30 1.71
3 amoeba 3 NA 3 3.60 1.30 1.71
4 bacterium 1 0 251 3.82 3.48 2.13
5 bacterium 2 0 252 3.82 3.48 2.13
6 bacterium 3 0 253 3.82 3.48 2.13
7 leech 1 1 501 5.71 1.83 4.50
8 leech 2 1 502 5.71 1.83 4.50
9 leech 3 0 503 5.71 1.83 4.50