首页 > 解决方案 > Object not found - R

问题描述

I am trying to construct data.tree from json/dataframe I have got.

library(data.tree)
construct_tree <- function(x) {

  gq <- Node$new("sessions")
  for(i in 1:nrow(x)) {
    if(x[i,c("type")] != 'RECORD')
       gbq$AddChild(x[i,c("name")])
    else
      y <- as.data.frame(x[i,c('fields')])
      print(y)
  }
 gq
}

This is how the data looks,

dput(data_samp)
structure(list(name = c("date", "totals"), type = c("STRING", 
"RECORD"), fields = list(NULL, structure(list(mode = c("NULLABLE", 
"NULLABLE", "NULLABLE", "NULLABLE", "NULLABLE", "NULLABLE", "NULLABLE", 
"NULLABLE", "NULLABLE", "NULLABLE", "NULLABLE", "NULLABLE", "NULLABLE"
), name = c("visits", "hits", "pageviews", "timeOnSite", "bounces", 
"transactions", "transactionRevenue", "newVisits", "screenviews", 
"uniqueScreenviews", "timeOnScreen", "totalTransactionRevenue", 
"sessionQualityDim"), type = c("INTEGER", "INTEGER", "INTEGER", 
"INTEGER", "INTEGER", "INTEGER", "INTEGER", "INTEGER", "INTEGER", 
"INTEGER", "INTEGER", "INTEGER", "INTEGER")), .Names = c("mode", 
"name", "type"), class = "data.frame", row.names = c(NA, 13L)))), class = "data.frame", row.names = c(NA, 
-2L), .Names = c("name", "type", "fields"))

But in the else condition, when i try to use object 'y', i keep getting Error in print(y) : object 'y' not found

Can anyone advise what i am doing wrong here. Thanks.

标签: rjson

解决方案


You need an extra curly braces around the else condition statements:

library(data.tree)
construct_tree <- function(x) {

  gq <- Node$new("sessions")
  for(i in 1:nrow(x)) {
    if(x[i,c("type")] != 'RECORD')
       gbq$AddChild(x[i,c("name")])
    else{
      y <- as.data.frame(x[i,c('fields')])
      print(y)}
  }
 gq
}

推荐阅读