【问题标题】:How can I save list of lists in R to a file without losing the format?如何在不丢失格式的情况下将 R 中的列表列表保存到文件中?
【发布时间】:2020-12-02 08:01:03
【问题描述】:

如何将 R 中的列表列表存储到一个文件中,以便当我再次读取它时,它的格式与我存储它之前的格式完全相同? 这是对象在我保存之前的样子:

$parameters_model_r$cost_type
[1] "FTC"

$parameters_model_r$input_path
[1] "/mnt/OUTPUT/CPM_PET_US/MODEL/DATA"

$parameters_model_r$file_type
[1] "parquet"

$parameters_model_r$delimiter
[1] ","

$parameters_model_r$inferSchema
[1] "true"

$parameters_model_r$label
[1] "CASS_LINE_COST"

及其类型:str(config)

 $ parameters_model_r         :List of 22
  ..$ cost_type         : chr "FTC"
  ..$ input_path        : chr "/mnt/OUTPUT/CPM_PET_US/MODEL/DATA"
  ..$ file_type         : chr "parquet"
  ..$ delimiter         : chr ","
  ..$ inferSchema       : chr "true"
  ..$ label             : chr "CASS_LINE_COST"
  ..$ model_output_path : chr "/dbfs/mnt/OUTPUT/CPM_PET_US/MODEL/AGGREGATED_LEVEL/MODEL_OUTPUT"
  ..$ split_percentage  : num 0.75
  ..$ stratify_by       :List of 1
  .. ..$ columns: chr [1:3] "CUSTOMER" "PKGTECH" "REGION"
  ..$ glasso_stratify_by:List of 1
  .. ..$ columns: chr [1:2] "CUSTOMER" "PKGTECH"
  ..$ remove_cols       :List of 1
  .. ..$ columns: chr [1:5] "YEARPERIOD" "STRATIFY_BY" "YEARPERIODWEEK" "SEGMENTATION" ...
  ..$ n_folds           : int 10
  ..$ lambda_lower_bound: num 0.001
  ..$ lambda_upper_bound: num 0.01

理想情况下,我需要将其转换为 Json,但每次我使用 toJSON() 时,格式都会发生变化,然后当我读回它时,它不再起作用,因为在我的建模脚本中,所有内容都需要专门传入和我上面展示的一样

【问题讨论】:

  • 你可以使用saveRDS,文件只能从R读取

标签: r json list


【解决方案1】:

我不知道您使用了哪个确切的函数,但使用 jsonlite 包中的 toJSONfromJSON 函数似乎一切正常:

library(jsonlite)

# create nested list
my_list <- list(irisA = list(irisA1 = iris),
                irisB = list(irisB1 = iris),
                irisC = list(irisC1 = iris))

str(my_list, max.level = 2)

#> List of 3
#> $ irisA:List of 1
#> ..$ irisA1:'data.frame': 150 obs. of  5 variables
#> $ irisB:List of 1
#> ..$ irisB1:'data.frame': 150 obs. of  5 variables
#> $ irisC:List of 1
#> ..$ irisC1:'data.frame': 150 obs. of  5 variables

# convert to JSON
my_json <- jsonlite::toJSON(my_list)

# convert back
str(jsonlite::fromJSON(my_json), max.level = 2)

#> List of 3
#> $ irisA:List of 1
#> ..$ irisA1:'data.frame': 150 obs. of  5 variables
#> $ irisB:List of 1
#> ..$ irisB1:'data.frame': 150 obs. of  5 variables
#> $ irisC:List of 1
#> ..$ irisC1:'data.frame': 150 obs. of  5 variables

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多