1

我是 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;
}

非常感谢提前。

4

1 回答 1

2

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

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

现在,您可以使用mean(scores)来获取平均值。

于 2014-02-26T03:16:56.570 回答