Reputation: 2157
I'm using the table function in R to create a table of two of my variables in R. I have a data.frame like this
mytable
V1 V2 V3
1 a c
2 c d
3 b b
4 d a
5 d c
when I use the table function table(mytable$V2, mytable$V3) I get the following
a b c d
a 0 0 1 0
b 0 1 0 0
c 0 0 0 1
d 1 0 1 0
Now I actually want to treat situations 'a-b' the same as 'b-a'. Or 'b-c' the same as 'c-b'. Therefore I want to have a table where everything above the diagonal is empty. He needs to add the values from above the diagonal to the values below the diagonal. How can I do this in R?
And furthermore I want this table to be represented as a heatmap, which I normally do with ggplot2. But I don't know if this also works for a table that will have empty values above the diagonal.
Upvotes: 0
Views: 1037
Reputation: 132706
Here is the manual way of fixing it:
tab <- table(DF[,2:3])
tab[lower.tri(tab)] <- tab[lower.tri(tab)] + tab[upper.tri(tab)]
tab[upper.tri(tab)] <- NA
# V3
#V2 a b c d
# a 0
# b 0 1
# c 1 0 0
# d 1 0 2 0
Upvotes: 3