How to create an Array in R?

rstudio

#1

Create following data without using data.frame.

0123

Here is my script:

Row <-c("EXAM1","EXAM1","EXAM1","EXAM2","EXAM2","EXAM2")
Column <-c("","Math","Sci","Eng")
EXAM1 <- c("S001","S002" ,"S003" )
EXAM2<- c("S001","S002" ,"S003" )
Math <- c(90,100,100,80,0,60)
Sci <- c(80,100,40,0,50,100)
Eng <- c(70,60,0,99,0)
MyData <-array(c(EXAM1,EXAM2,Math,Sci,Eng),c(6,4),dimnames=list(Row, Column))
MyData

Can you please give me a feedback and correct me if I have made any mistake?
Should I use Matrix instead and why not? Can you please give me a different perspective? Thanks


#2

Your code is “correct” apart from a second missing 70 in Eng.
However, it will not be easy to work with that…

First, why don’t use data.frame ? . I am curious as your data here is made for data.frame.

In fact, in array or a matrix you cannot mix typed of values. In your case, everything will be considered as character because of the first column with "S001" and friends. You could take away the S to transform to numeric, and for Exam column to. You would have a matrix then. (a matrix is just an array of 2 dimension).

A dataframe structure we allow you to store columns of different types easily

EXAM <-c("EXAM1","EXAM1","EXAM1","EXAM2","EXAM2","EXAM2")
Column <-c("Exam", "Scen","Math","Sci","Eng")
Scen <- c("S001","S002" ,"S003", "S001","S002" ,"S003" )
Math <- c(90,100,100,80,0,60)
Sci <- c(80,100,40,0,50,100)
Eng <- c(70,60,70, 0,99,0)
MyData <-data.frame(EXAM,Scen,Math,Sci,Eng)
MyData
#>    EXAM Scen Math Sci Eng
#> 1 EXAM1 S001   90  80  70
#> 2 EXAM1 S002  100 100  60
#> 3 EXAM1 S003  100  40  70
#> 4 EXAM2 S001   80   0   0
#> 5 EXAM2 S002    0  50  99
#> 6 EXAM2 S003   60 100   0
str(MyData, 1)
#> 'data.frame':    6 obs. of  5 variables:
#>  $ EXAM: Factor w/ 2 levels "EXAM1","EXAM2": 1 1 1 2 2 2
#>  $ Scen: Factor w/ 3 levels "S001","S002",..: 1 2 3 1 2 3
#>  $ Math: num  90 100 100 80 0 60
#>  $ Sci : num  80 100 40 0 50 100
#>  $ Eng : num  70 60 70 0 99 0

Created on 2018-02-13 by the reprex package (v0.2.0).