rbindlapply

Can't Combine X <character> and X <double>


I am trying to merge various .csv files into one dataframe using the following: df<- list.files(path = "C:/Users...", pattern = "*.csv", full.names = TRUE) %>% lapply(read_csv) %>% bind_rows clean

However, I get an error saying that I can't combine X character variable and X double variable. Is there a way I can transform one of them to a character or double variable?

Since each csv file is slightly different, from my beginners standpoint, believe that lapply would be the best in this case, unless there is an easier way to get around this.

Thank you everyone for your time and attention!


Solution

  • You can change the X variable to character in all the files. You can also use map_df to combine all the files in one dataframe.

    library(tidyverse)
    
    result <- list.files(path = "C:/Users...", pattern = "*.csv", full.names = TRUE) %>% 
      map_df(~read_csv(.x) %>% mutate(X = as.character(X)))
    

    If there are more columns with type mismatch issue you can change all the columns to character, combine the data and use type_convert to change their class.

    result <- list.files(path = "C:/Users...", pattern = "*.csv", full.names = TRUE) %>% 
      map_df(~read_csv(.x) %>% mutate(across(.fns = as.character))) %>%
      type_convert()