1

I have a data frame with 2 columns that holds JSON like: I have 2 columns where each row in each column is a JSON.

df$col1[1] <- "[14,7,5,3,4,0,1,7,2,3,1,18,13,4,23,7,8,8,11,18,15,6,2,10,2,4,8,5,11,5,1,5,2,4,3,1,6,8,5,5,3,1,1,4,5,2,9,3,4,11,11,14,3,12,2,6,0,0,15,1,18,5,3,6,6,6]"

and a scalar column:

df$scalar <- 10, .... , 10

I want to apply the following formula:

((fromJSON(df$col1) / scalar1) / (fromJSON(df$col2) / scalar2))

I have done something like this:

lapply(df$col1, function(i) {fromJSON(i)/scalar1}) / 
lapply(df$col2, function(i) {fromJSON(i)/scalar2}

Is there any other way to do this?

steves
  • 331
  • 3
  • 16
  • Please review, I have a column of JSONs here! Not a JSON column! @akrun – steves Apr 15 '18 at 13:24
  • steves, your question is *close* but not [truly reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Could you add `dput(head(df[c("col1","col2","scalar1","scalar2")]))` (or whatever columns are required)? – r2evans Apr 15 '18 at 13:45

1 Answers1

2

We can loop through the columns that in JSON format apply fromJSON, then divide both with scalar using Map and Reduce it to a single vector

Reduce(`/`, Map(`/`, lapply(df[c('col1', 'col2')], fromJSON), df[c('scalar1', 'scalar2')]))

A similar approach using map from purrr would be

library(purrr)
map2(df[c('col1', 'col2')], df[c('scalar1', 'scalar2')], ~ fromJSON(.x)/.y) %>% 
                     reduce(`/`)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    Funny, you say "loop", and while I understand that often R does a literal `for` loop internally, I consider these not-loops from a conceptual stand-point. This is the structure of processing I had envisioning, perfectly elegant (IMO). – r2evans Apr 15 '18 at 12:44
  • There is an error: `Error: parse error: trailing garbage 2,2,6,0,0,15,1,18,5,3,6,6,6] [21,13,14,4,10,3,10,2,5,3,5,18, (right here) ------^` @akrun – steves Apr 15 '18 at 12:55
  • I have 2 columns where each row in each column is a JSON. – steves Apr 15 '18 at 12:59
  • @r2evans Maybe you can help? Each of my columns is contains JSONS - per row. – steves Apr 15 '18 at 13:14