Alium Britt
Alium Britt

Reputation: 1316

R - how to reference values in a table() nested in a list?

I'm generating a series of tables with the command table() that I'm storing together in a list, and I want to reference specific values of each table to use in calculation. I can correctly pull out the correct table from my list but I can't seem to find the correct way to reference the values within the table.

Here is my table (I don't think it matters, but I'm referencing this table within my list with code tables$'10'[1]):

[[1]]
          label.test
test_pred  Disorder Normal
  Disorder        7      4
  Normal          8     16

I'd like to be able to pull out one of those numbers, for example the 4 which seems like it would be referred to with [1,2]. I've tried nesting more brackets inside like this [1[1,2]], or chaining the square brackets one after another like this [1][1,2], or using more of the $ notation, but none of these have worked so far.

How can I reference the values in the table?

Upvotes: 2

Views: 2382

Answers (2)

Bing
Bing

Reputation: 1103

Not sure if you have a nested list which may need more attention. Without seeing your code, I guess you can try

 tables$'10'[1][[1]][1,2]

Upvotes: 2

LyzandeR
LyzandeR

Reputation: 37879

This should be clear enough:

b <- factor(rep(c("A","B","C"), 10))
table(b)
c <- factor(rep(c("A","B","C"), 10))
table(b)

tables <- list(table(b),table(c))

> tables
[[1]]
b
 A  B  C 
10 10 10 

[[2]]
c
 A  B  C 
10 10 10 

To access the first , second or third element of the first table:

> tables[[1]][1]
 A 
10 
> tables[[1]][2]
 B 
10 
> tables[[1]][3]
 C 
10 

It is the the same thing for the second table or any table. You need double square brackets [[]] at the beginning to access the element of the list

Upvotes: 1

Related Questions