R/Plotly:list2env(数据)中出错:第一个参数必须是命名列表



我对使用R有一定的经验,但我刚刚开始学习编写函数来自动化任务。我目前正在进行一个项目,对剩下的五位总统候选人的演讲进行情绪分析和主题模型,但遇到了障碍。

我写了一个function,逐句分析积极和消极的情绪,给每一句打分。神奇的是,它起了作用,给了我一个数据帧,每个句子都有分数。

    score        text
1     1        iowa, thank you.
2     2        thanks to all of you here tonight for your patriotism, for your love of country and for doing what too few americans today are doing.  
3     0        you are not standing on the sidelines complaining. 
4     1        you are not turning your backs on the political process.
5     2        you are standing up and fighting back.

所以我现在要做的是创建一个function,它取分数,计算出每个分数的计数代表的百分比,然后使用plotly绘制。这是我写的函数:

scoreFun <- function(x){{
  tbl <- table(x)
  res <- cbind(tbl,round(prop.table(tbl)*100,2))
  colnames(res) <- c('Score', 'Count','Percentage')
  return(res)
}
  percent = data.frame(Score=rownames, Count=Count, Percentage=Percentage)
  return(percent)
}

返回的是:

saPct <- scoreFun(sanders.scores$score)
saPct
     Count Percentage
-6     1       0.44
-5     1       0.44
-4     6       2.64
-3    13       5.73
-2    20       8.81
-1    42      18.50
0     72      31.72
1     34      14.98
2     18       7.93
3      9       3.96
4      6       2.64
5      2       0.88
6      1       0.44
9      1       0.44
11     1       0.44

我希望它返回的是一个数据帧,其中rownames是一个名为Score的变量,接下来的两列分别称为CountPercentage。然后我想使用以下代码在x轴上绘制Score,在y轴上绘制Percentage

d <- subplot(
  plot_ly(clPct, x = rownames, y=Percentage, xaxis="x1", yaxis="y1"),
  plot_ly(saPct, x = rownames, y=Percentage, xaxis="x2", yaxis="y2"),
  margin = 0.05,
  nrows=2
) %>% layout(d, xaxis=list(title="", range=c(-15, 15)),
             xaxis2=list(title="Score", range=c(-15,15)),
             yaxis=list(title="Clinton", range=c(0,50)),
             yaxis2=list(title="Sanders", range=c(0,50)),showlegend = FALSE)
d

我敢肯定,我在functionplot_ly代码中犯了一些明显的错误,因为很明显,它没有返回我想要的数据帧,并且在我运行`plotly代码时导致了错误Error in list2env(data) : first argument must be a named list。不过,我在编写函数方面经验不足,在谷歌搜索时也没有发现类似的问题,所以我不知道如何解决这个问题。

欢迎提出任何建议。谢谢

@MLavoie,我在评论中引用的问题中的这段代码成功了。非常感谢!

scoreFun <- function(x){
  tbl <- data.frame(table(x))
  colnames(tbl) <- c("Score", "Count")
  tbl$Percentage <- tbl$Count / sum(tbl$Count) * 100
  return(tbl)
}

最新更新