Save a data frame with list-columns as csv file

前端 未结 5 757
清歌不尽
清歌不尽 2021-02-09 06:01

I have the following data frame that looks like this (3 columns as list).

A tibble: 14 x 4
                                                    clinic_name drop_         


        
5条回答
  •  囚心锁ツ
    2021-02-09 06:51

    Create a tibble containing list columns:

    library(tibble)
    
    clinic_name <- c('bobo center', 'yoyo plaza', 'lolo market')
    drop_in_hours <- list(c("Monday: 2 pm - 5 pm", "Tuesday: 4 pm - 7 pm")) 
    appointment_hours <- list(c("Monday: 1 pm - 2 pm", "Tuesday: 2 pm - 3 pm")) 
    services <- list(c("skin graft", "chicken heart replacement"))
    
    tibb <- data_frame(clinic_name, drop_in_hours, appointment_hours, services)
    
    print(tibb)
    

    Write a general-purpose function that converts any list columns to character type:

    set_lists_to_chars <- function(x) {
        if(class(x) == 'list') {
        y <- paste(unlist(x[1]), sep='', collapse=', ')
        } else {
        y <- x 
        }
        return(y)
    }
    

    Apply function to tibble with list columns:

    new_frame <- data.frame(lapply(tibb, set_lists_to_chars), stringsAsFactors = F)
    
    new_frame
    

    Write newly formatted dataframe as csv file:

    write.csv(new_frame, file='Desktop/clinics.csv')
    

    This is a csv file with the list columns expanded as regular strings.

    Here is an all-encompassing function. Just pass in your tibble and a filename:

    tibble_with_lists_to_csv <- function(tibble_object, file_path_name) {
        set_lists_to_chars <- function(x) { 
            if(class(x) == 'list') { y <- paste(unlist(x[1]), sep='', collapse=', ') } else { y <- x  } 
            return(y) }
        new_frame <- data.frame(lapply(tibble_object, set_lists_to_chars), stringsAsFactors = F)
        write.csv(new_frame, file=file_path_name)
    }
    

    Usage:

    tibble_with_lists_to_csv(tibb, '~/Desktop/tibb.csv')
    

提交回复
热议问题