I have json
files with data for countries. One of the files has the following data:
我有json文件包含国家/地区的数据。其中一个文件包含以下数据:
"[{\"count\":1,\"subject\":{\"name\":\"Namibia\",\"alpha2\":\"NA\"}}]"
I have the following code convert the json
into a data.frame
using the jsonlite
package:
我有以下代码使用jsonlite包将json转换为data.frame:
df = as.data.frame(fromJSON(jsonfile), flatten=TRUE))
I was expecting a data.frame
with numbers and strings:
我期待一个带有数字和字符串的data.frame:
count subject.name subject.alpha2
1 Namibia "NA"
Instead, the NA
alpha2 code is being automatically converted into NA
logical, and this is what I get:
相反,NA alpha2代码自动转换为NA逻辑,这就是我得到的:
str(df)
$ count : int 1
$ subject.name : chr "Namibia"
$ subject.alpha2: logi NA
I want alpha2 to be a string, not logical. How do I fix this?
我希望alpha2是一个字符串,而不是逻辑。我该如何解决?
1 个解决方案
#1
1
That particular implementation of fromJSON (and there are three different packages with that name for a function) has a simplifyVector argument which appears to prevent the corecion:
fromJSON的特定实现(并且有三个不同的包具有该函数的名称)有一个simplifyVector参数,它似乎阻止了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"
I tried seeing if that option worked well with the flatten
argument, but was disappointed:
我试着看看这个选项是否适用于扁平化的论点,但是很失望:
> 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"
#1
1
That particular implementation of fromJSON (and there are three different packages with that name for a function) has a simplifyVector argument which appears to prevent the corecion:
fromJSON的特定实现(并且有三个不同的包具有该函数的名称)有一个simplifyVector参数,它似乎阻止了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"
I tried seeing if that option worked well with the flatten
argument, but was disappointed:
我试着看看这个选项是否适用于扁平化的论点,但是很失望:
> 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"