首页 > 解决方案 > 为什么 R 中的函数仅返回 R 列表绘图对象中的最后一个列表项

问题描述

我正在尝试在 R 中创建一个函数,并希望返回一个绘图对象列表。但它似乎只返回最后一个。

似乎我的空列表 dm_plots 造成了问题。我曾经dm_plots[[i]]分配每个地块,然后在最后返回它们。如果我明确地将每个图分配给p1p2等,它可以返回正确的列表。但是,它只返回最后一个图。

示例代码:

library(haven)
library(plotly)
            
dm <-read_sas('adsl.sas7bdat')
stats_vars <-c('BMI', 'HEIGHT')
            
dm1 <-dm %>%
select(stats_vars)
            
var_types <-sapply(dm1, class)
            
create.plot <- function(inset, xx=NULL, yy=NULL, yanse =NULL, zhu =NULL, xtitle=NULL, ytitle  = NULL ) {
            
nn <-length(yy)
               
dm_plots <-vector("list", length(stats_vars)) ## this empty list  created problem here?
for (i in 1:nn){
                  
dm_plots[[i]] <- plot_ly( inset         ,
                         x           = ~get(xx),
                         y           = ~get(yy[i]),
                         color       = ~yanse,
                         legendgroup = ~zhu,
                         type        = "box",
                         # boxmean =T,
                         boxmean     ='sd',
                         hoverinfo   = "y",
                         width       = 900
            
                ) %>%
      layout(boxmode = "group", boxgap=0.01) %>%
      layout(xaxis = list(title = xtitle, zeroline=F, titlefont=list(size=15) ),  
             showlegend = F,
             yaxis = list(title = ytitle, zeroline=F)  
             )
            
              }
              return(list(sapply(1:nn, function(i)list(dm_plots[[i]]))))
            }
            
output <- create.plot(dm, xx='TRT01P', yy= stats_vars, yanse='TRT01P', zhu='TRT01P', 
                      xtitle ='Treatment', ytitle='count')

标签: rlistfunctionreturnplotly

解决方案


推荐阅读