我有一些列表:
my_list1 <- list("data" = list(c("a", "b", "c")), "meta" = list(c("a", "b")))
my_list2 <- list("data" = list(c("x", "y", "z")), "meta" = list(c("x", "y")))
我希望能够对这些列表执行一些操作,但是我需要使用存储在向量中的列表名称,因为我是通过API调用动态创建它们的。这样的向量可能是:
list_vec <- c("my_list1", "my_list2")
我遇到了将向量中的字符串评估为列表名称的问题。我知道已经讨论了该主题,但是我特别坚持的部分是,在data
中运行函数时,只能提取assign
子列表。本质上是这样的情况:
library(purrr)
for(i in seq_along(1:length(list_vec))){
assign(list_vec[[i]], map_df(list_vec[[i]][["data"]], unlist))
}
将给出以下结果:
# A tibble: 3 x 1
data
<chr>
1 a
2 b
3 c
我还可以做类似的事情:
my_list1$meta <- NULL
使用
list_vec[[1]][["meta"]] <- NULL
要将列表简化为data
子列表,但我不能在动态分配的名称之内。
我也用eval
包裹了东西,但无法正常工作。
因此,具体地说,我需要从字符串中评估列表的名称,以便从中提取子列表。
答案 0 :(得分:1)
我们可以将向量class StandingViewController: UIViewController {
@IBOutlet weak var yearLabel: UILabel!
@IBOutlet weak var firstLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!
@IBOutlet weak var thirdLabel: UILabel!
@IBOutlet weak var fouthLabel: UILabel!
@IBOutlet weak var fifthLabel: UILabel!
var standing = ""
let standingDataModel = WeatherDataModel()
var currentUrl = ""
let SEASON_URL = "https://ergast.com/api/f1"
//let format = ".json"
override func viewDidLoad() {
super.viewDidLoad()
yearLabel.text = standing
userEnteredNewYear(standing: standing)
// Do any additional setup after loading the view.
}
//MARK: - Networking
/***************************************************************/
//Write the getStandingData method here:
func getStandingData (url: String) {
Alamofire.request(url, method: .get).responseJSON {
response in
if response.result.isSuccess {
print("Success we got the data!")
let standingJSON : JSON = JSON(response.result.value!)
print(standingJSON)
self.updateStandingData(json: standingJSON)
} else {
print("Error \(String(describing: response.result.error))")
self.yearLabel.text = "Connection Issues"
}
}
}
//Mark: JSON Parsing
func updateStandingData(json: JSON) {
if case standingDataModel.season = json["MRData"]["StandingsTable"]["season"].intValue {
standingDataModel.firstDriver = json["DriverStandings"][0]["Driver"]["driverId"].stringValue
updateUIWithStandingData()
} else {
yearLabel.text = "No data available"
}
}
//Mark user entered data.
func userEnteredNewYear(standing: String) {
currentUrl = SEASON_URL + "/" + String(standing) + "/driverstandings.json"
getStandingData(url: currentUrl)
}
func updateUIWithStandingData() {
yearLabel.text = "\(standingDataModel.season)"
firstLabel.text = standingDataModel.firstDriver
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
传递给list_vec
,它返回一个嵌套列表。我们使用mget
提取(lapply
)[[
元素,并使用data
将此嵌套列表转换为列表。
unlist
结果
unlist(lapply(mget(list_vec), `[[`, "data"), recursive = FALSE)