Ankit Solanki
Ankit Solanki

Reputation: 680

Converting Dataframe to LIST

I wish to convert a dataframe to list. Here's an example dataframe:

colname   name    age    address
1         John    22     Singapore
2         James   44     India
3         Jessie  21     Australia 

I would like to convert it to a list like:

Name : John Age: 22 Address: Singapore
Name : James Age: 44 Address India
Name : Jessie Age: 21 Address: Australia.

So basically I wish to get an aggregate of column name and corresponding value of the row in a single R datatype.

as.list didn't work for me.

Upvotes: 4

Views: 10684

Answers (1)

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

you can simply use:

 apply(X, 1, function(r) paste(names(X), r, sep=":", collapse=" "))

where X is your data.frame

If you do not want the first column in the output, add the appropriate [, -1] and [-1] respectively:

apply(X[, -1], 1, function(r) paste(names(X)[-1], r, sep=":", collapse=" "))

[1] "name:John age:22 address:Singapore"  
[2] "name:James age:44 address:India"     
[3] "name:Jessie age:21 address:Australia"

However, if your goal is to get this into JSON, you can use the rjson package:

library(rjson)
apply(X[,-1], 1, toJSON)

Which would give you an appropriately quoted string:

cat( apply(X[,-1], 1, toJSON) )

{"name":"John","age":"22","address":"Singapore"} 
{"name":"James","age":"44","address":"India"}
{"name":"Jessie","age":"21","address":"Australia"}

Upvotes: 6

Related Questions