Leo96
Leo96

Reputation: 499

Error in transforming tables to data.frame

I know they are other posts on converting tables to data frames with

as.data.frame.matrix()

I've to data frames; lets say df1 and df2. I want to calculate frequency tables of a specific column of the data frames and then merge the resulted tables into a data.frame oder matrix.

 foo1 <-table(droplevels(df1$h_MAR)) #calculating frequency of a column
 foo2 <-table(droplevels(df2$h_RMSR)) #calculating frequency of a column


foo1
h=24 h=12 h=53 h=21 h=25 h=18 h=29 h=30 h=48 
1    1    2    1    1    1    1    1    1 

foo2
h=23 h=47 h=35 h=52 h=33 h=29 h=24 h=37 h=48 
1    2    1    1    1    1    1    1    1 

I tried now transforming them to data.frames to rbind them. A "simple" rbind would give me the wrong result:

rbind(foo1,foo2)
       h=24 h=12 h=53 h=21 h=25 h=18 h=29 h=30 h=48
foo1    1    1    2    1    1    1    1    1    1
foo2    1    2    1    1    1    1    1    1    1

the error in:

as.data.frame.matrix(foo1)

Error in seq_len(ncols) : 
 argument must be coercible to non-negative integer

Note: The droplevels is in there to remove frequencies with zero Count.

Do you have any ideas how to merge them in a smart way without of loosing information ? It's important to me, that the results are in a data.frame for further calculations.

Here the dputs of foo1 and foo2:

dput(foo1)

structure(c(1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L), .Dim = 9L, .Dimnames =     structure(list(
c("h=24", "h=12", "h=53", "h=21", "h=25", "h=18", "h=29", 
"h=30", "h=48")), .Names = ""), class = "table")

dput(foo2)

structure(c(1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Dim = 9L, .Dimnames = structure(list(
c("h=23", "h=47", "h=35", "h=52", "h=33", "h=29", "h=24", 
"h=37", "h=48")), .Names = ""), class = "table")

Upvotes: 1

Views: 369

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76575

Maybe the following will do what you want.
I believe it is possible to generalize the code below to any other number of rows, but you only ask for two, foo1 and foo2 so here it goes.

all <- unique(c(names(foo1), names(foo2)))
result <- as.data.frame(matrix(NA, ncol = length(all)))
names(result) <- all
result[nrow(result), names(foo1)] <- foo1
result <- rbind(result, rep(NA, length(all)))
result[nrow(result), names(foo2)] <- foo2

result
#  h=24 h=12 h=53 h=21 h=25 h=18 h=29 h=30 h=48 h=23 h=47 h=35 h=52 h=33 h=37
#1    1    1    2    1    1    1    1    1    1   NA   NA   NA   NA   NA   NA
#2    1   NA   NA   NA   NA   NA    1   NA    1    1    2    1    1    1    1

Upvotes: 1

jhvdz
jhvdz

Reputation: 186

Does this solve your problem?

library(dplyr)
df1 <- data.frame(foo1)
df2 <- data.frame(foo2)
df12 <- full_join(df1, df2, by = c('Var1' = 'Var1')) %>%
        arrange(Var1)

Upvotes: 0

Related Questions