开始使用免费开始使用

为矩阵命名

为方便记住 star_wars_matrix 中存的内容,您希望为行添加电影名称。这样不仅便于阅读数据,也有助于从矩阵中选择特定元素。

与向量类似,您可以为矩阵的行和列添加名称:

rownames(my_matrix) <- row_names_vector
colnames(my_matrix) <- col_names_vector

我们已为您准备了两个向量:regiontitles。您将分别使用它们为 star_wars_matrix 的列和行命名。

本练习是课程的一部分

R 入门

查看课程

练习说明

  • 使用 colnames() 将向量 region 作为 star_wars_matrix 的列名。
  • 使用 rownames() 将向量 titles 作为 star_wars_matrix 的行名。
  • 打印 star_wars_matrix,查看结果。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Box office Star Wars (in millions!)
new_hope <- c(460.998, 314.4)
empire_strikes <- c(290.475, 247.900)
return_jedi <- c(309.306, 165.8)

# Construct matrix
star_wars_matrix <- matrix(c(new_hope, empire_strikes, return_jedi), nrow = 3, byrow = TRUE)

# Vectors region and titles, used for naming
region <- c("US", "non-US")
titles <- c("A New Hope", "The Empire Strikes Back", "Return of the Jedi")

# Name the columns with region


# Name the rows with titles


# Print out star_wars_matrix
编辑并运行代码