Horv
Horv

Reputation: 184

Make a data.frame from 3 data.frames in R

I have a problem in R, that I can't figure out how to solve. I have 3 data frames for example:

data1 = 
Stuff Freq
X     12 
Y     3
Z     4

data2 = 
Stuff Freq
X     6 
Y     5
W     8

data3 = 
Stuff Freq
Z     7
Y     4

And I want to make one data.frame from these, that looks like this:

data = 
Stuff  Freq1  Freq2  Freq3    
X         12      6      0
Y          3      5      7
Z          4      0      4
W          0      8      0

I tried this:

data <- as.data.frame(c(data1[,1], data2[,1], data3[,1]), cbind(data1[,2], data2[,2], data3[,2])); 

but it didn't work. Is there any possible way to solve this?

Upvotes: 1

Views: 68

Answers (2)

Roland
Roland

Reputation: 132874

You are looking for merge:

data1 <- data.frame(Stuff=c("X","Y","Z"), Freq=c(12,3,4)) 
data2 <- data.frame(Stuff=c("X","Y","W"), Freq=c(6,5,8)) 
data3 <- data.frame(Stuff=c("Z","Y"), Freq=c(7,4)) 

res <- merge(merge(data1, data2, by="Stuff", all=TRUE), 
             data3, by="Stuff", all=TRUE)
names(res)[-1] <- paste0("Freq", 1:3)

res[is.na(res)] <- 0

#   Stuff Freq1 Freq2 Freq3
# 1     X    12     6     0
# 2     Y     3     5     4
# 3     Z     4     0     7
# 4     W     0     8     0

Upvotes: 2

agstudy
agstudy

Reputation: 121598

the same idea as Roland but one liner solution and general for any number of data.frames:

  Reduce(function(x,y){
            res <- merge(x,y,by=1,all=T)
            res[is.na(res)] <- 0
            res
        },
     mget(ls(pattern='data.*')))
  Stuff Freq.x Freq.y Freq
1     X     12      6    0
2     Y      3      5    4
3     Z      4      0    7
4     W      0      8    0

Upvotes: 1

Related Questions