user3570187
user3570187

Reputation: 1773

Create csv file from a list in R

I have a data frame with the following variables:

   id<- c('A', 'B', 'C', 'll')
   location<- list(c('newyork', 'boston'), c('london','paris'), NULL, c('mumbai'))

  df<- data.frame(id, location)
  write.csv(df, file='test.csv')

I want to create a csv file from the data frame but i am getting error as the location is a list? Any ideas on how i can do this in R?

This sort of thing data structure was expected, if csv doesn't allow for nested structure it might be problematic. How about xls or xlsx?

  id location
  A  c(newyork, boston)
  B  c(london, paris)
  C  Null 
  D  c('mumbai')

Upvotes: 0

Views: 241

Answers (1)

d.b
d.b

Reputation: 32538

Run paste to combine elements in location. Then everything can be the same.

id<- c('A', 'B', 'C', 'll')
location<- list(c('newyork', 'boston'), c('london','paris'), NULL, c('mumbai'))
location = paste(location,sep = "")
df = data.frame(id,location)
write.csv(df, file='test.csv')
#> df
#  id               location
#1  A c("newyork", "boston")
#2  B   c("london", "paris")
#3  C                   NULL
#4 ll                 mumbai

The csv will look like below:

"","id","location"
"1","A","c(""newyork"", ""boston"")"
"2","B","c(""london"", ""paris"")"
"3","C","NULL"
"4","ll","mumbai"

You can cleanup further if you want

Upvotes: 2

Related Questions