Robbie Voort
Robbie Voort

Reputation: 141

Merge two tables but keep both values

I can't seem to figure out how to merge two tables into one table but keeping both values in one column. Perhaps someone can push me in the right direction on how to resolve this? Any ideas would be helpfull!

So I have the first table:

set0 <- data.frame(A = c("A", "B", "C", "D", "A", "B", "C", "D", "A", "B"),
                         B = c("E", "F", "G", "H", "I", "E", "F", "G", "H", "I"))

set0 <- table(transform(set0, 
                B = ifelse(B %in% c('F', 'G'), 'V', 
                           ifelse(B %in% c('H', 'I'), 'R', B))))
#> set0
#   B
#A   E R V
#  A 1 2 0
#  B 1 1 1
#  C 0 0 2
#  D 0 1 1

The table has the following values:

> str(set0)
 'table' int [1:4, 1:3] 1 1 0 0 2 1 0 1 0 1 ...
 - attr(*, "dimnames")=List of 2
  ..$ A: chr [1:4] "A" "B" "C" "D"
  ..$ B: chr [1:3] "E" "R" "V"

And I have the second table (with the same values as above):

cset0 <- chisq.test(set0)$expected
#   B
#A     E   R   V
#  A 0.6 1.2 1.2
#  B 0.6 1.2 1.2
#  C 0.4 0.8 0.8
#  D 0.4 0.8 0.8

I'd like to merge these tables to something like this:

#A       E         R         V
#  A  1 [0.6]   2 [1.2]   0 [1.2]
#  B  1 [0.6]   1 [1.2]   1 [1.2]
#  C  0 [0.4]   0 [0.8]   2 [0.8]
#  D  0 [0.4]   1 [0.8]   1 [0.8]

I've tried to make a CrossTable [gmodels] but as with that I cant figure out how to get the same outcome as set0 as shown above. I am quite new at merging tables as I never had to do this before. So any ideas are welcome.

Upvotes: 1

Views: 78

Answers (2)

akrun
akrun

Reputation: 886938

Using paste

set0[] <- paste0(set0, '[', cset0, ']')

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388817

If this is for display purposes you can use sprintf :

set0[] <- sprintf('%s [%s]', set0, cset0)
set0

# B
#A        E       R       V      
#  A 1 [0.6] 2 [1.2] 0 [1.2]
#  B 1 [0.6] 1 [1.2] 1 [1.2]
#  C 0 [0.4] 0 [0.8] 2 [0.8]
#  D 0 [0.4] 1 [0.8] 1 [0.8]

Upvotes: 2

Related Questions