Reputation: 1249
I have a few tables that count the frequency of eye color across three dataframes. I thought I could translate those tables in dataframes, then merge them as a new dataframe. I believe is the error is coming from the fact that I transformed the tables into dataframes and merge seems to add on the rows of it. But I need:
Color Tb1 Tb2 Tb3
Bl 5 0 3
Blk 6 7 0
Small condition is that not each dataframe has Black or Blue eye colors in it. So I need to account for that, then change the NA's to 0's.
I have tried:
chart<-merge(tb1,tb2,tb3)
chart
Error in fix.by(by.x, x) :
'by' must specify one or more columns as numbers, names or logical
AND
chart<-merge(tb1,tb2,tb3,all=T)
chart
Error in fix.by(by.x, x) :
'by' must specify one or more columns as numbers, names or logical
Example code:
one<-c('Black','Black','Black','Black','Black','Black','Blue','Blue','Blue','Blue','Blue')
two<-c('Black','Black','Black','Black','Black','Black','Black')
three<-c('Blue','Blue','Blue')
tb1<-table(one)
tb2<-table(two)
tb3<-table(three)
tb1<-as.data.frame(tb1)
tb2<-as.data.frame(tb2)
tb3<-as.data.frame(tb3)
Upvotes: 0
Views: 109
Reputation: 2864
You can convert all tables directly into one tibble using bind_rows
from the package dplyr
:
# creating the setup given in the question
one<-c('Black','Black','Black','Black','Black','Black','Blue','Blue','Blue','Blue','Blue')
two<-c('Black','Black','Black','Black','Black','Black','Black')
three<-c('Blue','Blue','Blue')
tb1<-table(one)
tb2<-table(two)
tb3<-table(three)
# note that there is no need for individual dataframes
# bind the rows of the given tables into a tibble
result <- dplyr::bind_rows(tb1, tb2, tb3)
# replace NAs with 0 values
result[is.na(result)] <- 0
# check the resulting tibble
result
# # A tibble: 3 x 2
# Black Blue
# <dbl> <dbl>
# 1 6 5
# 2 7 0
# 3 0 3
Upvotes: 2
Reputation: 2829
Doing it your way, I will do something as follows (column names are needed to be corrected):
newframe <- merge(tb1, tb2, by.x ="one", by.y ="two", all = TRUE)
merge(newframe, tb3, by.x ="one", by.y ="three", all = TRUE)
However, for nicer ways, check dplyr()
joins.
Upvotes: 1