使用JSON文件嵌套for循环
我认为以前没有人问过这个问题,我似乎找不到 我有一个嵌套的JSON文件,我想从中提取某些值。我玩弄了使用JSON文件嵌套for循环,json,r,for-loop,Json,R,For Loop,我认为以前没有人问过这个问题,我似乎找不到 我有一个嵌套的JSON文件,我想从中提取某些值。我玩弄了sapply,最后决定使用嵌套的for循环序列,如下所示: for(Factor in fund$Factors) { print(Factor$Name) for(FactorGroup in Factor$FactorGroups) { print(FactorGroup$Name) for(Model in FactorGroup$Models)
sapply
,最后决定使用嵌套的for循环
序列,如下所示:
for(Factor in fund$Factors)
{
print(Factor$Name)
for(FactorGroup in Factor$FactorGroups)
{
print(FactorGroup$Name)
for(Model in FactorGroup$Models)
{
print(Model$Name )
for(Position in Model$Positions)
{
print(Position$Symbol)
print(Position$Quantity)
print(Position$Risk)
print(Position$MaxRisk)
print(Position$Daysleft)
}
}
}
}
使用它,我可以准确地提取我需要的内容,但它是逐行提取的,因此输出如下所示:
[1] "factor 1"
[1] "factor group 1"
[1] "model"
[1] "position 1"
[1] 1
[1] -769.1946
[1] -7433.627
[1] 14
[1] "position 2"
[1] 5
[1] -3724.63
[1] -12062.5
[1] 76
这种情况持续了大约900条线路。我想知道的是,他们是否是一个更好的方式来组织这个输出。理想情况下,我希望将每个完整序列连接成一个向量,然后转到下一个循环。例如,上面的输出内容如下:
[1] "factor 1" - "factor group 1" - "model" - "position 1" - 1 - -769.1946 - -7433.627 - 14
[1] "factor 1" - "factor group 1" - "model" - "position 2" - 5 - -3724.63 - -12062.5 - 76
这将迭代,直到它在整个文件中循环(例如,通过因子2、因子组等)
谢谢 尝试使用
cat
代替print
。然后在最后一个右括号之前,添加
cat(“\n”)
print
每次使用新行时都会打印它cat
将附加到同一行
示例脚本
for(Factor in fund$Factors)
{
cat(Factor$Name)
cat(" - ")
for(FactorGroup in Factor$FactorGroups)
{
cat(FactorGroup$Name)
cat(" - ")
for(Model in FactorGroup$Models)
{
cat(Model$Name )
cat(" - ")
for(Position in Model$Positions)
{
cat(Position$Symbol)
cat(" - ")
cat(Position$Quantity)
cat(" - ")
cat(Position$Risk)
cat(" - ")
cat(Position$MaxRisk)
cat(" - ")
cat(Position$Daysleft)
}
}
}
cat("\n")
}
请提供您需要的是
cat
,它不会在输出中添加新行。cat(位置$Symbol“\n”)我知道这不正确,但不确定您的意思。哦,我想这就是您的意思:cat(位置$Symbol,sep=“\n”)这不是我的意思\n将添加一个新行,所以您只希望在最外层的循环中添加该行。您可能需要一个列表,其中每个列表项都是每个因子的数据向量。