r语言中列表中,有按日期排列的每个城市的数据。现在城市不变,日期打乱,数组重新排列。怎么弄呢?

Python013

r语言中列表中,有按日期排列的每个城市的数据。现在城市不变,日期打乱,数组重新排列。怎么弄呢?,第1张

dimnames用list给予赋值即可。如dimnames=list(rownames,colnames,...)。

R语言数组array函数:

数组是一个可以在两个以上的维度存储数据的R数据对象。例如 - 如果创建尺寸(2,3,4)的数组,那么创建4个矩形矩阵每2行3列。数组只能存储数据类型。使用 array()函数创建数组。它需要向量作为输入,并使用 dim 参数的值,以创建一个数组。

示例:

我们可以通过使用dimnames参数给予名称添加到数组中的行,列和矩阵。

# Create two vectors of different lengths.

vector1 <- c(5,9,3)

vector2 <- c(10,11,12,13,14,15)

column.names <- c("COL1","COL2","COL3")

row.names <- c("ROW1","ROW2","ROW3")

matrix.names <- c("Matrix1","Matrix2")

# Take these vectors as input to the array.

result <- array(c(vector1,vector2),dim=c(3,3,2),dimnames = list(column.names,row.names,matrix.names))

print(result)

当我们上面的代码执行时,它产生以下结果:

1. , , Matrix1

ROW1 ROW2 ROW3

COL15 10 13

COL29 11 14

COL33 12 15

2. , , Matrix2

ROW1 ROW2 ROW3

COL15 10 13

COL29 11 14

COL33 12 15

1000个苹果,每9个抽1个,抽30个,那也就用到9*30=270,跟1000有什么关系?

#假设apple原先是按顺序排的

>apple

[1] 1  2   3   4   ...

#首先将1000个苹果打乱顺序

>apple <- apple[sample(1000)] apple

[1]   528  376  9  231  ...

#然后写个循环

> count <- 0   # 这是最后抽出的样本数

> i <- 1   # 这是抽样范围的起点

> output <- vector() # 存储最后抽出来的样本

> while (count != 30){

+ temp <- sample(apple[i : (i + 8)] , 1)   # 在apple的第i到第i+8之间抽1个

+ output <- c(output, temp)  # 把结果存下来

+ i <- i + 9  # 重新设定起点

+ count <- count + 1  

}

运行完看output