I am learning R now and I want to make a matrix to store scores. I don't know why the named_matrix can't show the Student_6. The picture as below shows the Student_NA.
scores <- c(58, 46, 50, 90, 42, 52, 62, 44, 96, 92, 54, 82)
scores_matrix <- matrix(scores, nrow = 2,ncol = length(scores)/2, byrow = TRUE)
scores_matrix
named_matrix <- scores_matrix
suffix <- seq(1:n)
rownames(named_matrix) <- paste("Quiz_",suffix[1:nrow(named_matrix)],seq=" ")
colnames(named_matrix)<- paste("Student_",suffix[1:ncol(named_matrix)],seq=" ")
named_matrix
CodePudding user response:
n is undefined in your code. Also 1:n makes seq redundant.
Correcting your code -
scores <- c(58, 46, 50, 90, 42, 52, 62, 44, 96, 92, 54, 82)
scores_matrix <- matrix(scores, nrow = 2,ncol = length(scores)/2, byrow = TRUE)
scores_matrix
named_matrix <- scores_matrix
suffix <- 1:length(scores)
rownames(named_matrix) <- paste("Quiz_",suffix[1:nrow(named_matrix)],seq=" ")
colnames(named_matrix)<- paste("Student_",suffix[1:ncol(named_matrix)],seq=" ")
named_matrix
# Student_ 1 Student_ 2 Student_ 3 Student_ 4 Student_ 5 Student_ 6
#Quiz_ 1 58 46 50 90 42 52
#Quiz_ 2 62 44 96 92 54 82
However, you can also simplify this process.
scores <- c(58, 46, 50, 90, 42, 52, 62, 44, 96, 92, 54, 82)
n <- 2
m <- length(scores)/2
scores_matrix <- matrix(scores, nrow = n,ncol = m,byrow = TRUE,
dimnames = list(paste0('Quiz_', seq_len(n)),
paste0('Student', seq_len(m))))
scores_matrix
# Student1 Student2 Student3 Student4 Student5 Student6
#Quiz_1 58 46 50 90 42 52
#Quiz_2 62 44 96 92 54 82
CodePudding user response:
Solution
Here I just used your code up to this point:
scores <- c(58, 46, 50, 90, 42, 52, 62, 44, 96, 92, 54, 82)
scores_matrix <- matrix(scores,
nrow = 2,
ncol = length(scores)/2,
byrow = TRUE)
scores_matrix
Then just entered the names like so:
colnames(scores_matrix) <- paste("Student", 1:6)
rownames(scores_matrix) <- c("Quiz 1", "Quiz 2")
scores_matrix
Which gives you this:
Student 1 Student 2 Student 3 Student 4 Student 5 Student 6
Quiz 1 58 46 50 90 42 52
Quiz 2 62 44 96 92 54 82
Alternative transpose format
Also if you prefer a column format, since it is in a matrix, you can simply make a transpose of the matrix like so:
t(scores_matrix)
Which creates this:
Quiz 1 Quiz 2
Student 1 58 62
Student 2 46 44
Student 3 50 96
Student 4 90 92
Student 5 42 54
Student 6 52 82

