BuildingJarl BuildingJarl - 4 months ago 15
R Question

R new table from list of tables

I have a variable which contains a list of tables:

list_of_tables
: t1, t2, t3, t4, t5, t6, etc

Each table in
list_of_tables
(t1, t2, ...) has 8 rows. E.g.

uuid | q_id | correct
-----------------------
1 | 1 | T
1 | 2 | T
1 | 3 | F
1 | 4 | F
1 | 5 | T
1 | 6 | F
1 | 7 | F
1 | 8 | T


What I would like to do is create a new table or data frame from
list_of_tables
where each row has correct score, which is based on the number of rows where correct == T.

E.g

uuid | c_score
--------------
1 | 50% (4 out of 8 correct)
2 | ...
3 | ...

Val Val
Answer Source

here's a R base solution:

# data
list_of_tables <- lapply(1:10,function(x)
 data.frame(uuid=rep(x,10),q_id=1:10,correct=sample(c(TRUE,FALSE),10,replace = T)))

> list_of_tables
[[1]]
   uuid q_id correct
1     1    1    TRUE
2     1    2   FALSE
3     1    3    TRUE
4     1    4    TRUE
5     1    5   FALSE
6     1    6   FALSE
7     1    7    TRUE
8     1    8   FALSE
9     1    9    TRUE
10    1   10    TRUE

[[2]]
   uuid q_id correct
1     2    1    TRUE
2     2    2   FALSE
3     2    3    TRUE
4     2    4   FALSE
5     2    5    TRUE
6     2    6    TRUE
7     2    7   FALSE
8     2    8    TRUE
9     2    9   FALSE
10    2   10   FALSE


new_t <- do.call(rbind,
                 lapply(list_of_tables,function(x) data.frame(uuid=unique(x$uuid),c_score = (sum(x$correct)/nrow(x))*100)))

In this case do.call puts everything back into a single DF ... but you can skip that if you want to keep the lists.

> new_t
   uuid c_score
1     1      60
2     2      50
3     3      80
4     4      70
5     5      70
6     6      40
7     7      60
8     8      50
9     9      50
10   10      50