重命名变量时使用 numlist 循环 [英] Using a numlist loop when renaming variables
问题描述
我正在尝试使用 tidyverse/dplyr 重命名 R 中的两种类型的变量.第一种类型var_a_year",我想将其重命名为sample_year".第二种变量var_b_7",我想重命名为index_year".
I´m trying to rename two types of variables in R using tidyverse/dplyr. The first type "var_a_year", I want to rename it as "sample_year". The second type of variable "var_b_7", I want to rename it as "index_year".
第二个变量var_b"第一年2004"从数字 7 开始.并且每年增加2.因此,对于 2005 年,第二种类型变量称为var_b_9".如图所示.
The second variable, "var_b" starts on the number 7 for the first year "2004". And increases by 2 for each year. So for year 2005, the second type variable is called "var_b_9" as shown.
我想使用循环来加快速度,而不是每年都写一行.
I would like to use a loop so I can make this faster instead of writting a line for each year.
非常感谢!
df <- df %>%
rename(
sample_2004 = var_a_2004, index_2004 = var_b_7,
sample_2005 = var_a_2005, index_2005 = var_b_9,
sample_2006 = var_a_2006, index_2006 = var_b_11,
sample_2007 = var_a_2007, index_2007 = var_b_13,
...
sample_2020 = var_a_2020, index_2020 = var_b_39)
推荐答案
无需使用循环.rename_with
可以解决问题:
There's no need to use a loop. rename_with
will do the trick:
df <- tibble(var_a_2004=NA, var_b_7=NA, var_a_2005=NA, var_b_8=NA)
renameA <- function(x) {
return(paste0("sample_", stringr::str_sub(x, -4)))
}
df %>% rename_with(renameA, starts_with("var_a"))
给予
# A tibble: 1 x 4
sample_2004 var_b_7 sample_2005 var_b_8
<lgl> <lgl> <lgl> <lgl>
1 NA NA NA NA
我会让您自行研究如何为您的 var_b_XXXX
列编写相应的函数.
I'll leave you to work out how to code the corresponding function for your var_b_XXXX
columns.
这篇关于重命名变量时使用 numlist 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!