【问题标题】:Averages of List in R scriptR脚本中列表的平均值
【发布时间】:2014-03-28 15:53:43
【问题描述】:

我是 R 新手,我正在尝试从 JSON 文件中获取学生分数并制作直方图并计算平均分数,但我不确定是否有更简单的方法可以从 JSON 字符串中获取所有分数做平均。以下是我的代码:

library("RJSONIO")

students='[{"SSN":"1234","score":99},{"SSN":"1235","score":100},{"SSN":"1236","score":84}]';
students <- fromJSON(students);

scores = list();
i = 1;

for (rec in students){
  scores[i]=rec$score;
  i=i+1;
}

非常感谢。

【问题讨论】:

    标签: r rscript


    【解决方案1】:

    您可以使用lapply函数从每个列表元素中提取score值,然后使用unlist将结果转换为向量:

    scores <- unlist(lapply(students, function(x) x$score))
    scores
    # [1]  99 100  84
    

    现在,您只需使用mean(scores) 即可获得平均值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多