I have data that looks like this
aList <- list(a1 = c("apple", "banana", "orange", "strawberry", "cherry"),
a2 = c("banana", "cherry", "apple"),
a3 = c("apple", "strawberry", "pineapple"),
a4 = c("raspberry", "strawberry", "apple"),
a5 = c("pineapple", "lemon", "orange", "banana", "apple"),
a6 = c("lemon", "apple", "blueberry"),
a7 = c("watermelon", "apple", "banana", "mango"),
a8 = c("mango", "cherry", "apple", "lemon"),
a9 = c("orange", "banana", "strawberry"),
a10 = c("mango", "strawberry"))
I'd like to get it into a vertical format, like what happens when you run this code:
vertical_data <- list()
for (x in names(aList)) {
for (y in aList[[x]]) {
if (is.null(vertical_data[[y]])) {
vertical_data[[y]] <- x
} else {
vertical_data[[y]] <- c(x, vertical_data[[y]])
}
}
}
vertical_data
I'd like each entry to tell me where the particular fruit occurs.
This was easy enough to do with a double for loop. But when I do the same thing with a nested lapply function, it looks like it doesn't modify the list (i.e. vertical_data) at all. Why is that? The reason I'd like to do this with an apply function is because it's faster. My actual dataset will have thousands of items, and "fruits". It'll take way too long with for loops.
I'd really appreciate the help.
Thanks