merge - Combine vectors and tables in R -
i encountered problem during simple merging task , i'm looking better solution. i'm creating tables series of surveys (which cannot merge). tables have same values, different dimensions.
the data below.
table x
x <- structure(c(44l, 167l), .dim = 2l, .dimnames = structure(list( c("similar", "compete")), .names = ""), class = "table")
table y
y <- structure(c(69l, 213l, 154l, 4l, 29l, 32l), .dim = c(3l, 2l), .dimnames = structure(list( c("other", "compete", "similar"), c("college", "no college" )), .names = c("", "")), class = "table")
table z
z <- structure(c(13l, 38l, 43l, 46l, 131l, 172l, 37l, 177l, 122l, 8l, 34l, 12l, 16l, 114l, 70l, 20l, 17l, 27l), .dim = c(3l, 6l ), .dimnames = structure(list(c("other", "compete", "similar" ), c("skipped", "democrat", "independent", "libertarian", "republican", "other")), .names = c("", "")), class = "table")
my solution use cbind
, take out disimilar columns so
cbind(y[-1,], x, z[-1,-1])
then learned in r, row names unreliable , table turns out different if order of cbind mixed up. makes creating table unreliable. i'd able merge 3 or more tables, without having worry order of merge messing data.
what better way of combining tables different dimensions?
i suspect there might great way data.table
or dplyr
haven't figured out.
thanks , please let me know if can make question more clear.
not sure if i'm missing point here , not sure how "automated" need process be, might helpful:
x <- structure(c(44l, 167l), .dim = 2l, .dimnames = structure(list( c("similar", "compete")), .names = ""), class = "table") y <- structure(c(69l, 213l, 154l, 4l, 29l, 32l), .dim = c(3l, 2l), .dimnames = structure(list( c("other", "compete", "similar"), c("college", "no college" )), .names = c("", "")), class = "table") z <- structure(c(13l, 38l, 43l, 46l, 131l, 172l, 37l, 177l, 122l, 8l, 34l, 12l, 16l, 114l, 70l, 20l, 17l, 27l), .dim = c(3l, 6l ), .dimnames = structure(list(c("other", "compete", "similar" ), c("skipped", "democrat", "independent", "libertarian", "republican", "other")), .names = c("", "")), class = "table") library(dplyr) library(tidyr) # create data frames tables x = data.frame(x) names(x) = c("group","x") y = data.frame(y) %>% spread(var2,freq) names(y)[1] = "group" z = data.frame(z) %>% spread(var2, freq) names(z)[1] = "group" # join data frames x %>% inner_join(y, by="group") %>% inner_join(z, by="group") # group x college no college skipped democrat independent libertarian republican other # 1 similar 44 154 32 43 172 122 12 70 27 # 2 compete 167 213 29 38 131 177 34 114 17
Comments
Post a Comment