从R

时间:2017-02-02 22:13:32

标签: r

我有一个包含以下变量的数据框:

   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')

我想从数据框创建一个csv文件,但由于该位置是一个列表,我收到错误?关于我如何在R中做到这一点的任何想法?

这种事物数据结构是预期的,如果csv不允许嵌套结构,它可能会有问题。 xls或xlsx怎么样?

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

1 个答案:

答案 0 :(得分:2)

运行paste以合并location中的元素。然后一切都可以是一样的。

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

csv如下所示:

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

如果需要,可以进一步清理