1

I am having some problems with R and nested lists. I want to have a dictionary like structure (or array).

I have 12 categories (1-12), and each of them has a list of items. I have a table with all my data and want to split it, to show it in different UI components. The table has x rows, and one column. The rowname is my item, the column value is my category.

Table:

rowname | value
"A"     | 3
"B"     | 1
"C"     | 2
"D"     | 3
"E"     | 2

What I want as result:

data = { [1] = ("B"); [2] = ("C", "E"); [3] = ("A", "D") }

What I tried:

#init list of empty lists
data <- list()
for(i in 1:12){
  data[i] <- list()
}

for(i in 1:nrow(myTable)){
  val <- myTable[i, 1]
  name <- rownames(myTable)[i];
  print(paste(val, "-", name))
  tmp <- data[val]
  tmp[[name]] <- name
  data[val] <- tmp
}
print(data)

What is the best way to achieve this. This is my first time using R, so I might be missunderstanding basic language constructs.

HectorLector
  • 1,851
  • 1
  • 23
  • 33
  • 6
    `split(Table$rowname, Table$value)` – Jaap Jun 01 '18 at 11:51
  • I feel stupid now, If you post this as an answer I will accept it. – HectorLector Jun 01 '18 at 11:55
  • Related https://stackoverflow.com/questions/9713294/split-data-frame-based-on-levels-of-a-factor-into-new-data-frames – zx8754 Jun 01 '18 at 11:59
  • Don't feel stupid. We all have had to start at the beginning. I also still learn new functions regularly. – Jaap Jun 01 '18 at 12:01
  • 1
    `split()` is perfect but since this is you are beginning to use R, maybe you also want to be familiar with `lapply()`. Here is a not as elegant solution as `split()` with `lapply()`: `valInd <- sort(unique(df$value)); result <- lapply(valInd, function(x) df[which(df[["value"]] == x), ][["rowname"]]); names(result) <- valInd;` – JdeMello Jun 01 '18 at 13:50

0 Answers0