4

我正在使用 R 的 Haven 包来读取带有user_na=TRUE. 该文件有许多带有值标签的字符串变量。在 R 中,只有第一个字符串变量 ( SizeofH1) 具有分配给它的正确值标签作为属性。不幸的是,我什至无法提供此数据的片段以使其完全可重现,但这是我在 PSPP 中看到的屏幕截图

PSPP 数据编辑器

以及str()R中的返回...

 $ SizeofH1:Class 'labelled'  atomic [1:280109] 3 3 3 3 ...
 ..- attr(*, "label")= chr "Size of Household ab 2002"
 ..- attr(*, "format.spss")= chr "A30"
 ..- attr(*, "labels")= Named chr [1:9] "1" "2" "3" "4" ...
 ..- attr(*, "names")= chr [1:9] "4 Persons" "2 Persons" "1 Person 50 years plus" "3 Persons" ...
 $ PROMOTIO: atomic  40 1 40 40 ...
 ..- attr(*, "label")= chr "PROMOTION"
 ..- attr(*, "format.spss")= chr "A30"
 $ inFMCGfr: atomic  1 1 1 1 ...
 ..- attr(*, "label")= chr "in FMCG from2011"
 ..- attr(*, "format.spss")= chr "A30"
 $ TRADESEG: atomic  1 1 1 1 ...
 ..- attr(*, "label")= chr "TRADE SEGMENT"
 ..- attr(*, "format.spss")= chr "A30"
 $ ORGANISA: atomic  111 111 111 111 ...
 ..- attr(*, "label")= chr "ORGANISATION"
 ..- attr(*, "format.spss")= chr "A30"
 $ NAME    : atomic  9 9 9 9 ...
 ..- attr(*, "label")= chr "NAME"
 ..- attr(*, "format.spss")= chr "A30"

我希望有人可以指出导致这种行为的任何可能原因。

4

2 回答 2

2

“语义”小插图有一些关于这个主题的有用信息。

library(haven)
vignette('semantics')

有几个选项可以获取值标签。我认为一个很好的例子是下面演示的示例,它使用了包中的map函数purrr(但也可以用它lapply来代替)

# Get data from spss file
df <- read_sav(path_to_file)

# get value labels
df <- map_df(.x = df, .f = function(x) {
  if (class(x) == 'labelled') as_factor(x)
  else x})
# get column names
colnames(df) <- map(.x = spss_file, .f = function(x) {attr(x, 'label')})
于 2018-04-03T16:43:07.743 回答
1

最好的方法是将您的 spss 文件保存为 CSV,然后在 R 中读取它。我之前遇到过这个问题,有些字符串没有正确读取 - 通常 SPSS 在字符串变量方面不是很聪明,这可能会导致问题。

于 2016-10-21T02:53:34.937 回答