简体   繁体   中英

Making a matrix that gives a vector as output? - R

The idea is that the matrix contains students (rows, studerende1,2,3 ), grades (columns, -3,00,02,4,7,10,12 ) and amount of assignments (column, antal opgaver ). I've made an empty vector which should be filled with final grades when returned.

The code should then sort grades like this:

  1. If student has 1 assignment, the final grade will be the one given for that particular assignment.
  2. If student has 2 assignments: final grade will be the greatest of the two.

Issue: How do I proceed with this? The function + return(gradesFinal) must include due to it being assignment related. Also the output should be a vector.

q <- matrix(c(1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,1,2,2), ncol=8)
rownames(q) <-(c("studerende1", "studerende2", "studerende3"))
colnames(q) <- c("-3", "00", "02", "4", "7", "10", "12", "antal opgaver")

finalG <- c()

computeFinalGrades <- function(grades) {
for (i in 1:length(q$antal opgaver)){
if (matrix$antal opgaver[i] = 1){
finalG <- append(finalG, '-3')

return(gradesFinal)

screenshot of matrix since the table-function isn't working for me

The following function returns a named vector of the grades as defined in the question. The names are the row names of the input matrix.

computeFinalGrades <- function(grades){
  grd <- colnames(grades)[-ncol(grades)]
  grd <- as.numeric(grd)
  x <- grades[, -ncol(grades)]
  apply(x, 1, function(i) max(grd[as.logical(i)]))
}

computeFinalGrades(q)
#studerende1 studerende2 studerende3 
#         -3           7          10 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM