我有一个大的带标签的 SPSS 文件,它有大约 800 个变量,包含所有元数据、标签、值、变量。我正在寻找一种将其编写为 json 格式而不丢失变量 txt、标签和值的方法。
这里是一个示例虚拟数据:
library(haven)
library(labelled)
df <- data.frame(
a = labelled(c(1, 1, 2, 3), labels = c(No = 1, Yes = 2)),
b = labelled(c(1, 1, 2, 3), labels = c(No = 1, Yes = 2, DK = 3)),
c = labelled(c(1, 1, 2, 2), labels = c(No = 1, Yes = 2, DK = 3)),
d = labelled(c("a", "a", "b", "c"), labels = c(No = "a", Yes = "b")),
e = labelled_spss(
c(1, 9, 1, 2),
labels = c(No = 1, Yes = 2),
na_values = 9 ))
df1 <- df %>%
set_variable_labels( a = "txt1- Do you use xxx?") %>%
set_variable_labels( b = "txt2-Do you use xxx?") %>%
set_variable_labels( c = "txt3-Do you use xxx?") %>%
set_variable_labels( d = "txt4-Do you use xxx?") %>%
set_variable_labels( e = "txt5-Do you use xxx?")
如果我使用
jsonlite::write_json()
我可以将文件导出为 json,但我会丢失标签和其他元数据。有没有办法将其与元数据变量标签,值标签等导出到json文件
library(jsonlite)
exportJSON <- toJSON(df1)
write_json(exportJSON, "output.json")
最佳答案
serializeJSON()
允许将 R 对象转换为 JSON,保持所有数据和属性完整(但不包括环境)。可以使用 unserializeJSON()
恢复数据。
library(labelled)
library(jsonlite)
library(tibble)
df1 <- df1 %>%
as_tibble() # For prettier printing of labels
# Write json file
write(serializeJSON(df1), file = "dat.json")
# Restore
unserializeJSON(readLines("dat.json"))
# A tibble: 4 x 5
a b c d e
* <dbl+lbl> <dbl+lbl> <dbl+lbl> <chr+lbl> <dbl+lbl>
1 1 [No] 1 [No] 1 [No] a [No] 1 [No]
2 1 [No] 1 [No] 1 [No] a [No] 9 (NA)
3 2 [Yes] 2 [Yes] 2 [Yes] b [Yes] 1 [No]
4 3 3 [DK] 2 [Yes] c 2 [Yes]
关于r - 将 SPSS 数据中的标签和值导出为 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71139693/