I am a beginner of R. I want to create a 3 dimensional array but I can not define the length of each dimension. I am analysing students' marks in a class. There are 10 classes but it has a different number of students. And "Grade" will be 100-90, 89-80, 79-70... until there will be any student who got the relevant marks. I was going to use a couple of for-loops with the multiple array. If I create a 3 dim array,
我是r的初学者,我想创建一个三维数组,但是我不能定义每个维度的长度。我正在分析班上学生的成绩。有10个班,但学生人数不同。“等级”将是100-90,89-80,79-70…直到有学生拿到相关的分数。我要用多个数组的for循环。如果我创建一个3个dim数组,
arr<-array(data, dim=c(??,??,??)), dimnames= list("class","grade","average Marks") )
2 个解决方案
#1
4
You really do not want to use a matrix for this. A dataframe allows you to have a mixture of data types.
你真的不想用矩阵来做这个。dataframe允许您拥有混合的数据类型。
clasIDs <- c("Firsthour", "Secondhour", "Thirdhour")
class.size <-c(3, 5, 2) # small sizes for illustration
cls.frame <- data.frame(clasID=rep(clasIDs, class.size),
student.ID = unlist(sapply(class.size, function(x) seq(from=1, to=x))),
grade=factor(rep(NA,10) , levels=c("100-90", "89-80", "79-70")) )
> cls.frame
clasID student.ID grade
1 Firsthour 1 <NA>
2 Firsthour 2 <NA>
3 Firsthour 3 <NA>
4 Secondhour 1 <NA>
5 Secondhour 2 <NA>
6 Secondhour 3 <NA>
7 Secondhour 4 <NA>
8 Secondhour 5 <NA>
9 Thirdhour 1 <NA>
10 Thirdhour 2 <NA>
#2
2
You can't.
你不能。
Array are of fixed dimensions. You could use the maximum along each dimension and allocate that along with NA
to fill in.
阵列的尺寸是固定的。您可以使用每个维度上的最大值并将其与NA一起分配来填充。
Lists are the alternative for varying lengths, and even different component types.
对于不同的长度,甚至不同的组件类型,列表都是可选的。
#1
4
You really do not want to use a matrix for this. A dataframe allows you to have a mixture of data types.
你真的不想用矩阵来做这个。dataframe允许您拥有混合的数据类型。
clasIDs <- c("Firsthour", "Secondhour", "Thirdhour")
class.size <-c(3, 5, 2) # small sizes for illustration
cls.frame <- data.frame(clasID=rep(clasIDs, class.size),
student.ID = unlist(sapply(class.size, function(x) seq(from=1, to=x))),
grade=factor(rep(NA,10) , levels=c("100-90", "89-80", "79-70")) )
> cls.frame
clasID student.ID grade
1 Firsthour 1 <NA>
2 Firsthour 2 <NA>
3 Firsthour 3 <NA>
4 Secondhour 1 <NA>
5 Secondhour 2 <NA>
6 Secondhour 3 <NA>
7 Secondhour 4 <NA>
8 Secondhour 5 <NA>
9 Thirdhour 1 <NA>
10 Thirdhour 2 <NA>
#2
2
You can't.
你不能。
Array are of fixed dimensions. You could use the maximum along each dimension and allocate that along with NA
to fill in.
阵列的尺寸是固定的。您可以使用每个维度上的最大值并将其与NA一起分配来填充。
Lists are the alternative for varying lengths, and even different component types.
对于不同的长度,甚至不同的组件类型,列表都是可选的。