Reputation: 388
I have a data frame as follows:
I want to create a list of maps from the data frame. Below is the code I am using now:
list_tot <- list()
list_tot[[1]] <- list()
list_tot[[1]][['arId']] <- "AR-3739"
list_tot[[1]][['lrIds']] <- list()
list_tot[[1]][['lrIds']][[1]] <- "LR-125423"
list_tot[[2]] <- list()
list_tot[[2]][['arId']] <- "AR-3764"
list_tot[[2]][['lrIds']] <- list()
list_tot[[2]][['lrIds']][[1]] <- "LR-125424"
list_tot[[3]] <- list()
list_tot[[3]][['arId']] <- "AR-3678"
list_tot[[3]][['lrIds']] <- list()
list_tot[[3]][['lrIds']][[1]] <- "LR-125425"
jsonData <- toJSON(list_tot)
Below is the output:
"[{\"arId\":\"AR-3739\",\"lrIds\":[\"LR-125423\"]},{\"arId\":\"AR-3764\",\"lrIds\":[\"LR-125424\"]},{\"arId\":\"AR-3678\",\"lrIds\":[\"LR-125425\"]}]"
One "AR ID" can have several "LR ID", i.e., for each row, "LR ID" is unique, while "AR ID" can have duplicates. Could you please let me know whether there is a convenient way to do that if there are quite a few rows in the data frame. Thank you for your help.
Upvotes: 0
Views: 48
Reputation: 66
This isn't the most elegant solution, but it should work no matter how many rows you have in your data frame. First, I've turned your excel table into a data frame:
df <- data.frame(
AR_ID = c("AR-3739", "AR-3764", "AR-3678"),
LR_ID = c("LR-125423", "LR-125424", "LR-125425")
)
Then, to get your desired output:
library(dplyr)
get_sublist <- function(small_df) {
list(arId = unique(small_df$AR_ID), lrIds = as.list(small_df$LR_ID))
}
unique_arids <- unique(df$AR_ID)
list_tot <- lapply(
X = unique_arids,
FUN = function(arid) {
df %>%
filter(AR_ID == arid) %>%
get_sublist()
}
)
jsonData <- toJSON(list_tot)
Upvotes: 1