0

I have a very unfriendly list and need to convert it into a df (res) for further processing.

The structure of the columns is always the same with value, count, value.1,count.1......etc. Ideal form of the dataframe:

value count value.1 count.1 value.2 count.2
1      12    1        6        1     5
2      3     2        4        2     6
3      4     3        5        3     8  
4      7                       4     3
5      8

So far , I have tried do.call(c, lapply(res, rownames)) and unlist(lapply(res, rownames)) but it just gets mixed up and seperated in the wrong colums. In the following code, I nearly get there:

require(reshape2)
res$value<- rownames(res) 
b<-melt(res)

and the output looks like this:

Var1 Var2  value  L1
1    value   2     1
2    value   5     1 
3    count   1     1
4    count   2     1 
5    value   7     2
6    value   9     2 
7    count   10    2
8    count   2     2 
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lucas
  • 1
  • 2
    You should provide an example data set that you are starting with. You are showing us what you want, and what you have been able to do, but not a great example of what data you are starting with. Please provide that. – JMT2080AD May 30 '18 at 17:05

1 Answers1

0

One example:

library(dplyr)
res <- structure(list(value = 1:5, count = c(12L, 3L, 4L, 7L, 8L), value.1 = 1:4, 
                      count.1 = c(6L, 4L, 5L, 3L), value.2 = 1:3, count.2 = c(5L, 6L, 8L)), 
                 .Names = c("value", "count", "value.1", "count.1", "value.2", "count.2"))

lapply(1:length(res), function(i) {
  data.frame(Var1=seq_along(res[[i]]), Var2=names(res)[i], value=res[[i]], stringsAsFactors = F)
}) %>% do.call(rbind, .)

   Var1    Var2 value
1     1   value     1
2     2   value     2
3     3   value     3
4     4   value     4
5     5   value     5
6     1   count    12
7     2   count     3
8     3   count     4
9     4   count     7
10    5   count     8
11    1 value.1     1
12    2 value.1     2
13    3 value.1     3
14    4 value.1     4
15    1 count.1     6
16    2 count.1     4
17    3 count.1     5
18    4 count.1     3
19    1 value.2     1
20    2 value.2     2
21    3 value.2     3
22    1 count.2     5
23    2 count.2     6
24    3 count.2     8
thc
  • 9,527
  • 1
  • 24
  • 39