我有要编辑的嵌套列表。为此,我想使用unlist
和relist
。问题是relist
似乎不尊重底层结构:
# Some list
my_list <- list(vec = 'string',
df = data.frame(X=0,Y=0,Z=0))
str(my_list)
# List of 2
# $ vec: chr "string"
# $ df :'data.frame': 1 obs. of 3 variables:
# ..$ X: num 0
# ..$ Y: num 0
# ..$ Z: num 0
# Unlist to modify nested content
my_unlist <- unlist(my_list)
str(my_unlist)
# Named chr [1:4] "string" "0" "0" "0"
# - attr(*, "names")= chr [1:4] "vec" "df.X" "df.Y" "df.Z"
# Write some data
my_unlist[c("df.X","df.Y","df.Z")] <- c(0,1,1)
str(my_unlist)
# Named chr [1:4] "string" "0" "1" "1"
# - attr(*, "names")= chr [1:4] "vec" "df.X" "df.Y" "df.Z"
# Relist
my_relist <- relist(flesh = my_unlist, skeleton = my_list)
str(my_relist)
# List of 2
# $ vec: chr "string"
# $ df : Named chr [1:3] "0" "1" "1"
# ..- attr(*, "names")= chr [1:3] "X" "Y" "Z"
重新列出时,您将看到列表元素df
(如果不再是数据框)。
这是一个手动解决方法
# A manual work-around
my_relist$df <- setNames(data.frame(t(as.numeric(my_relist$df)), stringsAsFactors = FALSE),
names(my_relist$df))
str(my_relist)
# List of 2
# $ vec: chr "string"
# $ df :'data.frame': 1 obs. of 3 variables:
# ..$ X: num 0
# ..$ Y: num 1
# ..$ Z: num 1
但是它没有太大帮助,因为我想任意执行此操作。
理想情况下,我有一个函数可以在保留结构的同时用my_list
的内容填充my_unlist
。所以预期的输出将是
my_relist
# $vec
# [1] "string"
#
# $df
# X Y Z
# 1 0 1 1
修改
以下是一些示例数据以及更详细的示例
# Sample data: a simple json
test_json <- '{
"email": "string",
"locations": [
{
"address": {
"city": "string",
"country": "string",
"houseNr": "string",
"state": "string",
"streetName": "string",
"zipCode": "string"
},
"latitude": 0,
"longitude": 0,
"name": "string"
}
],
"phone": "string"
}'
# Reading the json sample
json <- jsonlite::fromJSON(test_json)
# Now we unlist json so that we can easily modify nested elements
json_unlist <- unlist(json)
# Let's add a few address components
fields_to_modify <- c("locations.address.houseNr","locations.address.streetName","locations.address.city","locations.address.country")
json_unlist[fields_to_modify] <- c("1", "Boulevard de Londres","Casablanca","Morocco")
# Now we want to convert it back to json
# First step: we must relist
attempt <- relist(flesh = json_unlist, skeleton = json)
attempt$locations
# address latitude longitude name
# "Casablanca" "Morocco" "1" "string"
# <NA> <NA> <NA> <NA>
# "Boulevard de Londres" "string" "0" "0"
# <NA>
# "string"
答案 0 :(得分:1)
使用问题中的json
,请注意,例如,由于以下含义相同:
json[["locations"]][["address"]][["city"]]
json[[c("locations", "address", "city")]]
并假设在未列出对象的命名中使用点,如问题所示,我们可以像这样使用Map
:
setList <- function(List, Unlist) {
nms <- names(Unlist)
Map(function(x, y) List[[x]] <<- Unlist[[y]], strsplit(nms, "\\."), nms)
List
}
setList(my_list, my_unlist)
setList(json, json_unlist)