2015-05-05 19 views
6

Ho file json con dati per paesi. Uno dei file ha i seguenti dati:"NA" nel file JSON si traduce in NA logico

"[{\"count\":1,\"subject\":{\"name\":\"Namibia\",\"alpha2\":\"NA\"}}]" 

Ho il seguente codice convertire il json in un data.frame utilizzando il pacchetto jsonlite:

df = as.data.frame(fromJSON(jsonfile), flatten=TRUE)) 

mi aspettavo un data.frame con i numeri e stringhe:

count subject.name subject.alpha2 
1  Namibia    "NA" 

Invece, il codice alpha2 NA viene convertito automaticamente in NA logica, e questo è ciò che ottengo:

str(df) 
$ count   : int 1 
$ subject.name : chr "Namibia" 
$ subject.alpha2: logi NA 

voglio alpha2 di essere una stringa, non è logico. Come posso risolvere questo?

+1

Benvenuti in SO. buona prima domanda Prova ad aggiungere altri dati di esempio con cui le persone possono giocare. – vagabond

+1

Basta costringere a 'character'. Probabilmente non è necessario farlo perché R farà quella coercizione al primo bisogno. –

+0

@BondedDust Grazie. Sì, R richiede inizialmente la coercizione, ma ci sono alcuni file con solo dati per la Namibia. C'è un modo per forzare a 'character' quando si converte il json in' dataframe'? – Armin

risposta

1

Tale realizzazione particolare fromJSON (e ci sono tre diversi pacchetti con tale nome per una funzione) ha un argomento simplifyVector che sembra impedire il corecion:

require(jsonlite) 

> as.data.frame(fromJSON(test, simplifyVector=FALSE)) 
    count subject.name subject.alpha2 
1  1  Namibia    NA 
> str(as.data.frame(fromJSON(test, simplifyVector=FALSE))) 
'data.frame': 1 obs. of 3 variables: 
$ count   : int 1 
$ subject.name : Factor w/ 1 level "Namibia": 1 
$ subject.alpha2: Factor w/ 1 level "NA": 1 
> str(as.data.frame(fromJSON(test, simplifyVector=FALSE) ,stringsAsFactors=FALSE)) 
'data.frame': 1 obs. of 3 variables: 
$ count   : int 1 
$ subject.name : chr "Namibia" 
$ subject.alpha2: chr "NA" 

Ho cercato di vedere se tale opzione funzionava bene con l'argomento flatten, ma è stato deluso:

> str( fromJSON(test, simplifyVector=FALSE, flatten=TRUE)) 
List of 1 
$ :List of 2 
    ..$ count : int 1 
    ..$ subject:List of 2 
    .. ..$ name : chr "Namibia" 
    .. ..$ alpha2: chr "NA" 
+0

'simplifyVector = FALSE' ha fatto il trucco. Grazie. – Armin