4

我正在使用该haven库将.sav(SPSS)文件读入 R。

一些值被读取为labelled vector.

这是一个例子:

> str(df$instructional_practice)
Class 'labelled'  atomic [1:4136] 2 2 6 6 8 8 NaN NaN 17 1 ...
  ..- attr(*, "label")= chr "intructional practice teacher is using when signaled"
  ..- attr(*, "format.spss")= chr "F8.2"
  ..- attr(*, "labels")= Named num [1:18] 1 2 3 4 5 6 7 8 9 10 ...
  .. ..- attr(*, "names")= chr [1:18] "1 Lecture" "2 Seatwk-Ind" "3 Review-Ind" "4 Seatwk-Grp" ...

如何vector获得标签名称的值?

4

2 回答 2

7

您可以使用haven::as_factor标签作为级别将标签向量转换为因子。

您可以在单个向量上使用它:

df$instructional_practice = as_factor(df$instructional_practice)

但您也可以在整个 data.frame 上使用它。默认情况下as_factor,在 data.frame 上使用会将所有标签转换为任何标签变量的因子水平。

df = as_factor(df)
于 2016-12-27T14:56:33.913 回答
1

目前它非常像一个 R 因子,我猜(虽然它有点模糊)你想要一个 R 因子或者你想要一个字符向量。如果您想要一个 R 字符向量,其中的值替换当前数值,您可以使用数值作为labels属性名称的索引:

 newvec <- names( attr( f$instructional_practice , "labels"))[f$instructional_practice]
于 2016-12-23T19:28:17.497 回答