Search code examples
rrscript

Averages of List in R script


I'm new to R and I'm trying to get student scores from a JSON file and do histograms and calculate average score but I'm not sure if there is an easier way to get all scores from the JSON string to do the average. Below is my code:

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

Much thanks in advance.


Solution

  • You can use the lapply function to extract the score value from each list element, and then use unlist to convert the result to a vector:

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

    Now, you can just use mean(scores) to get the average.