How do I add the values of a Table

I was wondering how to add the values of a Two-Way table on R with out having to do it manually.

# This is the contents of my table, I want to add the values for '0' and '1' ONLY individually for each 'ticket.first.char' variable.
ticket.first.char   0   1 None
                1  54  92   64
                2  98  85   95
                3 229  72  128
                4   8   2    1
                5   3   0    0
                6   5   1    3
                7   8   1    4
                8   2   0    0
                9   0   1    1
                A  27   2   13
                C  31  16   30
                F   3   4    6
                L   3   1    1
                P  23  42   33
                S  44  21   33
                W  11   2    6

Are you just after a new column with:

  • 146 for the first row

  • 183 for the second row

and so on?

Can you create a reproducible example (using reprex or something similar)?

1 Like

No, I just want to add the values for the '0' and '1' columns with each other, for example take the first row (1 = 54 + 92 , 2 = 98 + 85)

Is this what you mean?

library(dplyr)

# Sample data on a copy/paste friendly format
sample_df <- data.frame(stringsAsFactors=FALSE, 
                        check.names = FALSE,
   ticket.first.char = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "C",
                         "F", "L", "P", "S", "W"),
                  `0` = c(54, 98, 229, 8, 3, 5, 8, 2, 0, 27, 31, 3, 3, 23, 44,
                         11),
                  `1` = c(92, 85, 72, 2, 0, 1, 1, 0, 1, 2, 16, 4, 1, 42, 21, 2),
                None = c(64, 95, 128, 1, 0, 3, 4, 0, 1, 13, 30, 6, 1, 33, 33, 6)
)

sample_df %>% 
    mutate(sum_0_1 = `0` + `1`)
#>    ticket.first.char   0  1 None sum_0_1
#> 1                  1  54 92   64     146
#> 2                  2  98 85   95     183
#> 3                  3 229 72  128     301
#> 4                  4   8  2    1      10
#> 5                  5   3  0    0       3
#> 6                  6   5  1    3       6
#> 7                  7   8  1    4       9
#> 8                  8   2  0    0       2
#> 9                  9   0  1    1       1
#> 10                 A  27  2   13      29
#> 11                 C  31 16   30      47
#> 12                 F   3  4    6       7
#> 13                 L   3  1    1       4
#> 14                 P  23 42   33      65
#> 15                 S  44 21   33      65
#> 16                 W  11  2    6      13

Created on 2020-01-16 by the reprex package (v0.3.0.9000)

If not, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

1 Like