为矩阵命名
为了帮助你记住 star_wars_matrix 中存了什么,你想把电影名称加到行名上。这样不仅能让数据更易于阅读,还方便你从矩阵中选取特定元素。
与向量类似,你可以为矩阵的行和列添加名称:
rownames(my_matrix) <- row_names_vector
colnames(my_matrix) <- col_names_vector
我们已为你准备了两个向量:region 和 titles。你需要分别使用这两个向量为 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