ichbinangela
ichbinangela

Reputation: 55

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.

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. (by using str) (showing only part of it)

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

I appreciate any help!

Upvotes: 0

Views: 2431

Answers (2)

Kestutis Vinciunas
Kestutis Vinciunas

Reputation: 63

pacman::p_load(tidyverse)

train.user %>% as_tibble() %>% mutate(age = map(age,~unlist(.)))

Upvotes: 0

Jonathan Carroll
Jonathan Carroll

Reputation: 3947

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.

NB: Don't edit an answer into your question.

Upvotes: 3

Related Questions