renkun-ken / rlist

A Toolbox for Non-Tabular Data Manipulation
Other
202 stars 28 forks source link

[Question] is there a better way to do this in rlist package? #112

Open happyshows opened 8 years ago

happyshows commented 8 years ago

Hi,

I was experimenting on d3radar package and encountered the following transformation need. I'm wondering if rlist has a more efficient way of achieving the same? The approach might have wider application as it's json like.

Thanks.

mtcars %>% add_rownames( var = "key" ) %>% mutate_each(funs(rescale), -key) %>%

limit to 8 rows for manageability

head(8) %>% by_row( function(row){ list( key = row[["key"]], values = lapply( names(row)[-match("key",names(row))], function(nm){ list( "axis" = nm, "value" = row[[nm]] ) } ) ) } )

http://www.buildingwidgets.com/blog/2015/12/9/week-49-d3radarr

timelyportfolio commented 8 years ago

I am sure that @renkun-ken probably has a more elegant answer, but here is my first way to do in rlist.

library(dplyr)
library(scales)
library(rlist)
library(d3radarR)

mtcars %>%
  add_rownames( var = "key" ) %>%
  mutate_each(funs(rescale), -key) %>%
  head(8) %>%
  list.parse() %>%
  list.map(
    list(
      "key"=key,
      values=lapply(
        names(.)[-match("key",names(.))],
        function(nm){
          list(
            "axis" = nm,
            "value" = .[[nm]]
          )
        }
      )
    )
  ) %>%
  unname() %>%
  d3radar()