使用 for 循环遍历列名将标签添加到 gt table
add labels to gt table with for loop over column names
我有以下数据 table .
library(dplyr)
library(gt)
df <- tibble(
`model 2000` = c("a", "b"),
`car 2022` = c("f", "d")
)
我想遍历列名向量并执行字符串替换,然后将其附加到 gt table
my_cols <- colnames(df)
for(i in my_cols){
df <- df %>%
gt() %>%
cols_label(
i = str_trim(str_remove(i, "2020|2021|2022"))
)
df
}
我希望能够在使用此 for 循环创建 GT table 后更改名称,但是当循环传递 my_cols 中的值时,它们无法被识别...有帮助吗?
这是错误:
Error: All column names provided must exist in the input `.data` table.
最好的方法是避免循环并传递一个命名向量并将其拼接在 cols_labels()
:
my_cols <- setNames(str_trim(str_remove(names(df), "2020|2021|2022")), names(df))
df %>%
gt() %>%
cols_label(!!!my_cols)
如果出于某种原因必须使用循环,则需要在循环外创建 gt()
对象,否则在第一次迭代后您传递的对象已经是 class gt_tbl
到导致错误的 gt()
函数。您还需要使用 Walrus 运算符 :=
而不是 =
并且 LHS 需要是符号或粘合字符串。
my_cols <- names(df)
df <- df %>%
gt()
for(i in my_cols) {
df <- df %>%
cols_label("{i}" := str_trim(str_remove(i, "2020|2021|2022"))) # or !!sym(i) := ...
}
df
您可以在 cols_label()
中使用 .list
选项。
my_cols <- colnames(df)
df %>%
gt() %>%
cols_label(
.list = setNames(as.list(str_trim(str_remove(my_cols, "2020|2021|2022"))), my_cols)
)
但是,这样做似乎更容易:
my_cols <- colnames(df)
df %>%
rename_with(~str_trim(str_remove(.x, "2020|2021|2022")), .cols =my_cols) %>%
gt()
输入:
df <- tibble(
`model 2021` = c("a", "b"),
`car 2022` = c("f", "d")
)
我有以下数据 table .
library(dplyr)
library(gt)
df <- tibble(
`model 2000` = c("a", "b"),
`car 2022` = c("f", "d")
)
我想遍历列名向量并执行字符串替换,然后将其附加到 gt table
my_cols <- colnames(df)
for(i in my_cols){
df <- df %>%
gt() %>%
cols_label(
i = str_trim(str_remove(i, "2020|2021|2022"))
)
df
}
我希望能够在使用此 for 循环创建 GT table 后更改名称,但是当循环传递 my_cols 中的值时,它们无法被识别...有帮助吗?
这是错误:
Error: All column names provided must exist in the input `.data` table.
最好的方法是避免循环并传递一个命名向量并将其拼接在 cols_labels()
:
my_cols <- setNames(str_trim(str_remove(names(df), "2020|2021|2022")), names(df))
df %>%
gt() %>%
cols_label(!!!my_cols)
如果出于某种原因必须使用循环,则需要在循环外创建 gt()
对象,否则在第一次迭代后您传递的对象已经是 class gt_tbl
到导致错误的 gt()
函数。您还需要使用 Walrus 运算符 :=
而不是 =
并且 LHS 需要是符号或粘合字符串。
my_cols <- names(df)
df <- df %>%
gt()
for(i in my_cols) {
df <- df %>%
cols_label("{i}" := str_trim(str_remove(i, "2020|2021|2022"))) # or !!sym(i) := ...
}
df
您可以在 cols_label()
中使用 .list
选项。
my_cols <- colnames(df)
df %>%
gt() %>%
cols_label(
.list = setNames(as.list(str_trim(str_remove(my_cols, "2020|2021|2022"))), my_cols)
)
但是,这样做似乎更容易:
my_cols <- colnames(df)
df %>%
rename_with(~str_trim(str_remove(.x, "2020|2021|2022")), .cols =my_cols) %>%
gt()
输入:
df <- tibble(
`model 2021` = c("a", "b"),
`car 2022` = c("f", "d")
)