将 Python 元组列表转换为 R 命名向量

Transforming Python list of tuples to R named vector

我有 python 网状函数,其中 returns 类型为 (id, name) 的两个长度元组列表。

# In the python API
returned_list = [
    (1, "Jon Doe"),
    (2, "Jane Doe"),
]
library(shiny)
library(reticulate)
# source and other staff

API <- pythonAPI()
values <- API.call() # Returns R list of 2 length lists
values
#   [,1]   [,2] 
# [1,] List,2 List,2
for(index in 1:length(values)){
    message(values[index])
# list(1, "Jon Doe")
# list(2, "Jane Doe")

这个 values 列表应该作为 shinyselectInput choices 参数的选择。此 choices 参数应将 name 作为显示给用户的值,并将 id 作为程序中处理的隐藏值。

selectInput("_id", "Choose name", choices)

如何转换从 Python API 返回的 values 以适应用例?

我的同事想出了解决办法。

# Create dataframe scaffold
df <- data.frame("name" = NA, "id" = NA)
# Bind values from values to the scaffold by rows
for (i in seq(values)) {
    df_tmp <- rbind.data.frame(values[[i]])
    colnames(df_tmp) <- c("name", "id")
    df <- rbind(df, df_tmp)
}

## Remove empty first row
df <- df[!is.na(df$name),]
    ​
# Transform to right format for shinyapp UI
choices <- setNames(df$name, df$id)