r - Converting Dataframe to LIST -
i wish convert dataframe list. here's example dataframe:
colname name age address 1 john 22 singapore 2 james 44 india 3 jessie 21 australia i convert list like:
name : john age: 22 address: singapore name : james age: 44 address india name : jessie age: 21 address: australia. so wish aggregate of column name , corresponding value of row in single r datatype.
as.list didn't work me.
you can use:
apply(x, 1, function(r) paste(names(x), r, sep=":", collapse=" ")) where x data.frame
if not want first column in output, add appropriate [, -1] , [-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 goal json, can use rjson package:
library(rjson) apply(x[,-1], 1, tojson) which give 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"}
Comments
Post a Comment