I want to take a list of lists and store the filenames with the keys from the original list, but I can't get the key to evaluate in the for loop. Here is my code:
input_metadata = list(dog = list(filename = "dog.png", rating = 7),
cat = list(filename = "kitty.png", rating = 9))
for (key in (names(input_metadata))) {
print(key)
print(input_metadata[[key]]$filename)
temp_list <- list( key
= input_metadata[[key]]$filename)
data_list <- append(data_list, temp_list)
}
print(data_list)
and here is the output:
[1] "dog"
[1] "dog.png"
[1] "cat"
[1] "kitty.png"
> print(data_list)
[[1]]
[1] NA
$key
[1] "dog.png"
$key
[1] "kitty.png"
This is close to what I want. I want to get rid of the initial NA and I want the keys to be dog and cat (the value of key), rather than "key". How can I make this happen?
How do I get the keys in data_list to match the keys in input_metadata?
CodePudding user response:
Provided I understood you correctly, you can do
Using purrr
data_list <- purrr::map(input_metadata, ~ .x$filename)
# Or
data_list <- purrr::map(input_metadata, purrr::pluck, "filename")
Or in base R
data_list <- lapply(input_metadata, function(x) x$filename)
# Or
data_list <- lapply(input_metadata, "[[", "filename")
# Or in R>=4.1.0
data_list <- lapply(input_metadata, \(x) x$filename)
All of the above give
#$dog
#[1] "dog.png"
#
#$cat
#[1] "kitty.png"