saruftw
saruftw

Reputation: 1174

Converting comma separated list to dataframe

If I have a list similar to x <- c("Name,Age,Gender", "Rob,21,M", "Matt,30,M"), how can I convert to a dataframe where Name, Age, and Gender become the column headers.

Currently my approach is,

dataframe <- data.frame(matrix(unlist(x), nrow=3, byrow=T))

which gives me

matrix.unlist.user_data...nrow...num_rows..byrow...T.
1                                        Name,Age,Gender
2                                         Rob,21,M
3                                        Matt,30,M

and doesn't help me at all.

How can I get something which resembles the following from the list mentioned above?

   +---------------------------------------------+
   |    name      |      age      |     gender   |
   |              |               |              |
   +---------------------------------------------+
   |              |               |              |
   |              |               |              |
   |     ...      |       ...     |     ...      |
   |              |               |              |
   |              |               |             ++
   +---------------------------------------------+
   |              |               |              |
   |     ...      |      ...      |   ...        |
   |              |               |              |
   |              |               |              |
   +---------------------------------------------+

Upvotes: 2

Views: 2295

Answers (2)

Uwe
Uwe

Reputation: 42564

Alternatively,

data.table::fread(paste(x, collapse = "\n"))
   Name Age Gender
1:  Rob  21      M
2: Matt  30      M

Upvotes: 4

akrun
akrun

Reputation: 887511

We paste the strings into a single string with \n and use either read.csv or read.table from base R

read.table(text=paste(x, collapse='\n'), header = TRUE, stringsAsFactors = FALSE, sep=',')

Upvotes: 4

Related Questions