renaming all dataframe columns with stringr and dplyr
我正在尝试使用
以下是完全可复制的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | library(dplyr) library(stringr) library(tibble) library(rlang) # dataframe x <- tibble::as.tibble(cbind( Grace_neu_wrong = c(1:4), Grace_acc_wrong = c(1:4), Grace_att_wrong = c(1:4), Grace_int_wrong = c(1:4) )) # defining custom function to rename the entire dataframe in a certain way string_conversion <- function(df, ...) { # preparing the dataframe df <- dplyr::select(.data = df, !!rlang::quo(...)) # custom function to split the name of each column in a certain way splitfn <- function(x) { x <- as.character(x) split <- stringr::str_split(string = x, pattern ="_")[[1]] paste(split[2], split[3], '_', split[1], sep = '') } # applying the splitfn function to each column name and outputting the data frame df_new <- df %>% dplyr::select_all(.funs = colnames) %>% dplyr::mutate_all(.funs = splitfn) return(df_new) } # the output I get string_conversion(df = x, names(x)) #> # A tibble: 4 x 4 #> Grace_neu_wrong Grace_acc_wrong Grace_att_wrong Grace_int_wrong #> <chr> <chr> <chr> <chr> #> 1 NANA_1 NANA_1 NANA_1 NANA_1 #> 2 NANA_1 NANA_1 NANA_1 NANA_1 #> 3 NANA_1 NANA_1 NANA_1 NANA_1 #> 4 NANA_1 NANA_1 NANA_1 NANA_1 # the output I desire tibble::as.tibble(cbind( neuwrong_Grace = c(1:4), accwrong_Grace = c(1:4), attwrong_Grace = c(1:4), intwrong_Grace = c(1:4) )) #> # A tibble: 4 x 4 #> neuwrong_Grace accwrong_Grace attwrong_Grace intwrong_Grace #> <int> <int> <int> <int> #> 1 1 1 1 1 #> 2 2 2 2 2 #> 3 3 3 3 3 #> 4 4 4 4 4 |
由reprex创建于2018-02-08
软件包(v0.1.1.9000)。
您可以在不使用mutate的情况下在一行中执行此操作,mutate应该用于列值而不是列名称。而是使用
因此,代码只有一行:
1 2 3 4 5 6 7 8 9 | names(x) <- str_replace(names(x),"(.*)_(.*)_(.*)","\\\\2\\\\3_\\\\1") print(x) # A tibble: 4 x 4 neuwrong_Grace accwrong_Grace attwrong_Grace intwrong_Grace <int> <int> <int> <int> 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 |