Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to turn a column of characters into a column of lists

In order to save a dataframe as a csv file, I had to convert a list-type column of the dataframe that was a list of vectors of different lengths and of different dates.
ex.
enter image description here

To be able to save the dataframe, I did DF$dates <- as.character(DF$dates) and then used write.csv() to save it. I want to be able to read in this file and use this column as a list column of vectors again, but the resulting column after reading in the file is a column of characters that is difficult to work with.
The rows are all variations of this: c("12/01/23", "12/02/23", "12/04/23", "12/05/23", "12/07/23", "12/13/23", "12/14/23", "12/15/23", "12/16/23", "12/17/23", "12/19/23", "12/20/23", "12/21/23", "12/22/23", "12/23/23", "12/24/23", "12/25/23", "12/30/23", "12/31/23")" which is just one long string that I am not able to use for much.

I’ve tried several things such as as.list() on a cell, using str_sub() to remove the parentheses, str_replace_all() to replace the backslashes, and strsplit() to separate the dates into different list objects and nothing has been simple or worked well enough.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can re-parse the contents of "dates" (c() and all) and reattach it in the following way. I’m not sure if you’re using dplyr or not, so here is a base R solution:

DF <- data.frame(dates = 'c("12/01/23", "12/02/23", "12/04/23", "12/05/23", "12/07/23", "12/13/23", "12/14/23", "12/15/23", "12/16/23", "12/17/23", "12/19/23", "12/20/23", "12/21/23", "12/22/23", "12/23/23", "12/24/23", "12/25/23", "12/30/23", "12/31/23")')

DF$dates_list <- lapply(DF$dates, \(x) eval(str2expression(x)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading