简体   繁体   中英

Rename_if column in R with prefix if name %in% list: lists do not match

I have a list of tibbles which have been created with map functions. The column names are as follows...

dfA[[1]]%>% colnames(.)  
[1] "date_strt"  "grouped_id" "10938_0"    "12881_0"   

The numbered column names create issues for a function I am using (mice), and I need to change them to have a string prefixed to the beginning. As I need to do this for a large number of tibbles I cannot reference the names directly. So I have created lists of character vectors from another tibbles names

df_list <- dfB %>% names() %>% as.vector()

Some of the names have the string "ITEM" prefixed, so I remove this for the matching list.

df_list <- purrr::map(df_list ,function(x){x %>% str_remove(.,"ITEM")})

When I attempt to then append according to the strings, we get some unwanted special characters

purrr::map2(dfA, df_list, function(df, name_list)
    df %>% rename_if(colnames(.) %in% name_list, ~paste0("ITEM", .)))

[[1]] date_strt           grouped_id `ITEM\`12881_0\`` `ITEM\`79916_0\``

I then use list to convert the name list (df_list) to list, as I have been told this is an issue.

df_list<- list(df_list)

This worked last night, however for some reason after restarting my session today (and updating my packages) it no longer works.

When I do a conditional check of row names

dfA[[1]][-1]%>% colnames(.) == df_list[[1]]

I get this before applying list

[1] FALSE  TRUE  TRUE

But this after

[1] FALSE FALSE FALSE

I do no know why but df_list[[1]] now returns both list times rather than just list [1]

before apply list

[1] "day"     "10938_0" "12881_0"

after apply list

[[1]]
[1] "day"     "10938_0" "12881_0"

[[2]]
[1] "day"     "12881_0" "79916_0"

Any suggestions as to why and how to fix it? Alternatively, its only columns which start with numbers that I need to append the prefix too, but I can't see an obvious solution.

here the str_remove is applied on the entire dataset and according to ?str_remove the input string would be

string - Input vector. Either a character vector, or something coercible to one

data.frame/tibble are not coercible to vector

This can be reproduced with a simple example

head(iris) %>% 
     str_remove("\\..*")
#[1] "c(5"                 "c(3"                 "c(1"                 "c(0"                 "c(1, 1, 1, 1, 1, 1)"

instead it should be applied on each column

library(dplyr)
library(purrr)
library(stringr)
purrr::map(df_list, ~ .x %>%
                          rename_all(~ str_remove(.,"ITEM")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM