拼接数据框
数据通常存储在数据框中。多数情况下,我们希望生成对人也友好的分析结果。例如,打印一句描述数据框规模的话就很有用。通过将 glue() 与 nrow() 和 ncol() 结合,您可以取出数值,并生成一句报告数据框维度的文字。
幸运的是,glue 包属于 tidyverse 集合,且在设计时就考虑了数据框,因此我们可以直接对整列进行操作。比如,可以在 mutate() 中使用它,创建一个新列,用拼接后的字符串包含其他列的取值。本练习中,您将把这些做法应用到 users 数据框上,其中包含其他列的取值。
本练习是课程的一部分
R 中级正则表达式
练习说明
- 使用
glue()函数报告users的行数和列数,并分别存入临时变量n和m。 - 仅运行打印列名的代码行,查看数据框
users。 - 对 users 执行 mutate,创建新列
n_logins,用name和logins两列分别报告用户登录的次数。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create two temporary variables "n" and "m" and use them
glue(
"The data frame 'users' has ___ rows and ___ columns.",
___ = nrow(users),
___ = ncol(users)
)
# This lists the column names of the data frame users
colnames(users)
# Use them to create a sentence about the numbers of logins
users %>% mutate(
n_logins = glue("___ logged in ___ times.")
)