我将这个问题分为两部分,第一部分是一般问题,第二部分是具体问题。
首先 - 我想知道是否有一种可能的方法来标记数字因子但仍保留其原始数字级别。这特别令人困惑,因为我意识到当我们将标签参数传递给一个因子时,它就会变成该因子的级别,例如:
x<- factor(c(1,2,3, 2, 3, 1, 2), levels = c(1, 2, 3), labels = c("a", "b", "c"))
levels(x)
#[1] "a" "b" "c"
labels(x)
#[1] "1" "2" "3" "4" "5" "6" "7"
我想知道是否有一种方法,就像Stata中那样,来标记一个因素的类别。我希望能够在 x 的元素显示为“a、”b 或“c”时对 x 求和,但保留值 1、2 或 3。
其次-我问这个是因为我有一个非常大的数据集,其中包含带有数字类别的列。该数据集附带一个 xlsx 字典,我将其读取并处理为 R,因此每一列都有其数字类别及其各自的标签。我正在尝试读取字典,在列列表中创建类别和标签列表,然后读取数据集,循环遍历列并标记变量。这些标签很重要,因此我不必每次解释数据集上的内容时都查看字典。数字级别很重要,因为由于我有很多虚拟变量(是或没有变量),我希望能够对它们求和。
这是我的代码(我使用 data.table 包):
dic<- readRDS(dictionary_filename)
# Reading data set #
data <- fread(dataset_filename, header = T, sep = "|", encoding = "UTF-8", na.strings = c("NA", ""))
# Treating the data.set #
# Identifying which lines of the dictionary have categorized variables. This is very specific to my dictionary strcture #
index<- which(!is.na(dic$num.categoria))
# storing the names of columns that have categorized variables #
names_var<- dic$`Var name`[index]
names_var<- names_var[!is.na(names_var)]
# Creating a data frame with categorized variables which will be later split into lists #
df<- as.data.frame(dic[index,])
# Transforming the index column to factor so it is possible to split the data frame into a list with sublists for each categorized column #
df$N<- as.factor(df$N)
# Splitting the data frame to list
lst<- split(df, df$N)
# Creating a labels list and a levels list #
lbs<- list()
lvs<- list()
for (i in 1:length(lst)){
lbs[[i]]<- as.vector(lst[[i]]$category)
lvs[[i]]<- as.vector(lst[[i]]$category.number)
}
# Changing the data set columns into factors with ther respective levels and labels #
k<- 1
for (var in names_var){
set(data, j =var, value = factor(data[[var]], levels = lvs[[k]], labels = lbs[[k]]))
k<- k +1
}
我意识到代码有点抽象,因为我不提供数据集或字典,但这只是为了让您有一个想法。我的代码可以工作,它运行时没有错误,并且执行了我希望执行的操作(所有分类列现在都显示其标签,例如,之前为 1 或 0 时为“是”或“否”)。除了我无法再访问级别中的原始数字这一事实之外,我需要在项目的下一部分中访问原始数字。
如果有一种通用的方法可以做到这一点,那就更好了,因为我在一个函数中运行此代码,其中许多列具有不同的数据集和不同的字典。有办法做到这一点吗?
PS.:我已阅读 R 中的文档以及这些问题的答案:
因子、水平和原始值
在 R 中使用 order 函数时遇到问题
但不幸的是,我自己无法弄清楚,很明显,在“factor”中使用“labels”参数并不是完成它的方法。
太感谢了!