简体   繁体   English

将包含列表的数据帧写入csv文件

[英]Write a data frame containing a list to csv file

I would like to save my data train.user (213451 obs. of 20 variables. 2 of the variables are lists) as a csv file. 我想将我的数据train.user (213451个变量,共20个变量。其中2个变量是列表)另存为csv文件。

I use: 我用:

write.csv(train.user, "train_user.csv", row.names = FALSE)

but an error occurs 但是发生错误

Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol,  : 
  unimplemented type 'list' in 'EncodeElement'

This is how my data train.user looks like. 这就是我的数据train.user样子。 (by using str ) (showing only part of it) (通过使用str )(仅显示其中一部分)

'data.frame':   213451 obs. of  20 variables:
 $ id                     : Factor w/ 213451 levels "00023iyk9l","0005ytdols",..: 100523 48039 26485 68504 48956 147281 129610 2144 59779 40826 ...
 $ gender                 : Factor w/ 4 levels "-unknown-","FEMALE",..: 1 3 2 2 1 1 2 2 2 1 ...
 $ age                    :List of 213451
  ..$ : num NA
  ..$ : num 38
  ..$ : num 56
  ..$ : num 42
  ..$ : num 41
  .. [list output truncated]

It seems like the column age is stored as a list, and write.csv doesn't accept this format. 似乎列age存储为列表,而write.csv不接受此格式。 From my naive intuition, I tried to re-store the column as a data frame with following code, but it failed. 出于天真的直觉,我尝试使用以下代码将列重新存储为数据框,但是失败了。

train.user$age <- as.data.frame(train.user$age)

Error message: 错误信息:

   Error in `$<-.data.frame`(`*tmp*`, "age", value = list(NA_real_. = NA_real_,  : 
  replacement has 1 row, data has 213451

I also tried train.user$age <- data.frame(lapply(train.user$age, unlist)) as suggested in another post, but the same error occurs. 我也尝试了train.user$age <- data.frame(lapply(train.user$age, unlist))如另一篇文章中所建议,但是发生相同的错误。

I appreciate any help! 感谢您的帮助!

train.user$age <- unlist(train.user$age)

Technically, a data.frame is a list of equal-length vectors, but most functions will assume that all of the columns are atomic vectors and will fail when you try to use a list. 从技术上讲, data.frame是等长向量的列表,但是大多数函数将假定所有列都是原子向量,并且在尝试使用列表时会失败。

NB: Don't edit an answer into your question. 注意:不要在问题中编辑答案。

pacman::p_load(tidyverse) pacman :: p_load(tidyverse)

train.user %>% as_tibble() %>% mutate(age = map(age,~unlist(.))) train.user%>%as_tibble()%>%mutate(年龄= map(年龄,〜unlist(。)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM