R:lapply和tibble在两个循环中无法按预期工作

时间:2019-03-15 12:33:54

标签: r lapply tibble

我有一组代码循环遍历我在闪亮的应用程序中用于向下钻取功能的所有可能情况。但是,Level_3_Drilldowns不能正常工作,因为我没有获得定义的tibble名称。

以下是Level_2_Drilldowns的单个输出,产生了预期的结果:

[[3]]
[[3]]$id
[1] "ocean"

[[3]]$type
[1] "column"

[[3]]$data
[[3]]$data[[1]]
[[3]]$data[[1]]$name
[1] "Boat"

[[3]]$data[[1]]$y
[1] 2

[[3]]$data[[1]]$PerTotal
[1] 37

[[3]]$data[[1]]$drilldown
[1] "ocean_boat"

在这里,我看到定义了nameyPerTotal(我需要能够在图形工具提示中引用它们)

以下是Level_3_Drilldowns的单个输出,不能产生预期的结果:

[[5]]
[[5]]$id
[1] "ocean_boat"

[[5]]$type
[1] "column"

[[5]]$data
[[5]]$data[[1]]
[[5]]$data[[1]][[1]]
[1] "Fig"

[[5]]$data[[1]][[2]]
[1] 1

[[5]]$data[[1]][[3]]
[1] 37


[[5]]$data[[2]]
[[5]]$data[[2]][[1]]
[1] "Tony"

[[5]]$data[[2]][[2]]
[1] 1

[[5]]$data[[2]][[3]]
[1] 37

您会看到nameyPerTotal未定义。

关于为什么不显示它们的任何想法吗?

下面是完整代码:

library (tidyr)
library (data.table)
library (highcharter)

x <- c("Farm","Farm","Farm","City","City","City","Ocean","Ocean")
y <- c("Sheep","Sheep","Cow","Car","Bus","Bus","Boat","Boat")
z <- c("Bill","Tracy","Sandy","Bob","Carl","Newt","Fig","Tony")
a <- c(1,1,1,1,1,1,1,1)
b <- c(3,5,1,3,8,5,3,9)

dat <- data.frame(x,y,z,a)


#First Tier #Copied
datSum <- dat %>%
  group_by(x) %>%
  summarize(Quantity = sum(a)
  )
datSum <- arrange(datSum,desc(Quantity))
Lvl1dfStatus <- tibble(name = datSum$x, y = datSum$Quantity, drilldown = tolower(name))


Level_2_Drilldowns <- lapply(unique(dat$x), function(x_level) {
  # x_level is what you called 'input' earlier.
  datSum2 <- dat[dat$x == x_level,]

  datSum2 <- datSum2 %>%
    group_by(y) %>%
    summarize(Quantity = sum(a),
              PerTotal = sum(b)
    )
  datSum2 <- arrange(datSum2,desc(Quantity))

  Lvl2dfStatus <- tibble(name = datSum2$y,y = datSum2$Quantity, PerTotal = datSum2$PerTotal, drilldown = tolower(paste(x_level, name, sep = "_")))

  list(id = tolower(x_level), type = "column", data = list_parse(Lvl2dfStatus))
})

Level_3_Drilldowns <- lapply(unique(dat$x), function(x_level) {

  datSum2 <- dat[dat$x == x_level,]

  lapply(unique(datSum2$y), function(y_level) {

    datSum3 <- datSum2[datSum2$y == y_level,]

    datSum3 <- datSum3 %>%
      group_by(z) %>%
      summarize(Quantity = sum(a),
                PerTotal = sum(b)
      )
    datSum3 <- arrange(datSum3,desc(Quantity))

    Lvl3dfStatus <- tibble(name = datSum3$z,y = datSum3$Quantity, PerTotal = datSum3$PerTotal)

    list(id = tolower(paste(x_level, y_level, sep = "_")), type = "column", data = list_parse2(Lvl3dfStatus))
  })
}) %>% unlist(recursive = FALSE)

0 个答案:

没有答案