cclams4444
cclams4444

Reputation: 27

Subsetting a table in R

In R, I've created a 3-dimensional table from a dataset. The three variables are all factors and are labelled H, O, and S. This is the code I used to simply create the table:

attach(df)
test <- table(H, O, S)

Outputting the flattened table produces this table below. The two values of S were split up, so these are labelled S1 and S2:

ftable(test)

+-----------+-----------+-----+-----+
|     H     |     O     | S1  | S2  |
+-----------+-----------+-----+-----+
| Isolation | Dead      |   2 |  15 |
|           | Sick      |  64 |  20 |
|           | Recovered | 153 | 379 |
| ICU       | Dead      |   0 |  15 |
|           | Sick      |   0 |   2 |
|           | Recovered |   1 |   9 |
| Other     | Dead      |   7 | 133 |
|           | Sick      |   4 |  20 |
|           | Recovered |  17 | 261 |
+-----------+-----------+-----+-----+

The goal is to use this table object, subset it, and produce a second table. Essentially, I want only "Isolation" and "ICU" from H, "Sick" and "Recovered" from O, and only S1, so it basically becomes the 2-dimensional table below:

+-----------+------+-----------+
|           | Sick | Recovered |
+-----------+------+-----------+
| Isolation |   64 |       153 |
| ICU       |    0 |         1 |
+-----------+------+-----------+
S = S1

I know I could first subset the dataframe and then create the new table, but the goal is to subset the table object itself. I'm not sure how to retrieve certain values from each dimension and produce the reduced table.

Edit: ANSWER

I now found a much simpler method. All I needed to do was reference the specific columns in their respective directions. So a much simpler solution is below:

> test[1:2,2:3,1]
                O
H                Sick Healed
  Isolation      64    153
  ICU            0     1

Upvotes: 0

Views: 501

Answers (1)

zx8754
zx8754

Reputation: 56149

Subset the data before running table, example:

ftable(table(mtcars[, c("cyl", "gear", "vs")]))
# vs  0  1
# cyl gear         
# 4   3        0  1
#     4        0  8
#     5        1  1
# 6   3        0  2
#     4        2  2
#     5        1  0
# 8   3       12  0
#     4        0  0
#     5        2  0

# subset then run table
ftable(table(mtcars[ mtcars$gear == 4, c("cyl", "gear", "vs")]))       
#          vs 0 1
# cyl gear       
# 4   4       0 8
# 6   4       2 2

Upvotes: 1

Related Questions