找不到对象-R

时间:2018-07-03 06:08:39

标签: r json

我正在尝试从已有的json / dataframe构造data.tree。

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
}

这就是数据的外观

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"))

但是在其他情况下,当我尝试使用对象“ y”时,我会不断得到Error in print(y) : object 'y' not found

有人可以告诉我我在做什么错。谢谢。

1 个答案:

答案 0 :(得分:1)

您需要在else条件语句周围加一个花括号:

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
}