R - 使用另一个向量替换一个因子的水平

R - Replacing levels of a factor using another vector

我有一个名为 "nationality" 的向量,它在我的数据框 (df) 中指示受访者的国籍。然而,问题在于它目前是一个从 1 到 193 的整数向量。我有另一个名为 "labels" 的行向量,其中包含每个国籍的标签(即第一列显示 "Afghan",第二个 "Albanian",等等)。我想要做的是将 "nationality" 向量转换为一个因子并将其数值替换为标签。我试过这个:

df$nationality <- as.factor(df$nationality)
labels2 <- names(labels)
levels(df$nationality) <- labels2

但它不起作用:(

请帮忙。提前致谢!

我做到了!但我不得不采取中间步骤,将带有 193 个国籍标签的文件手动保存为 xlsx 文件。这是我的解决方案:

## Creating data frame with 5 respondents and its corresponding nationalities (dim 5 x 2):

df <- data.frame(respondentId = c(1, 2, 3, 4, 5), nationality = c(166, 91, 4, 49, 128))

## Downloading nationality labels from guavastudios.com:

fileUrl <- "http://www.guavastudios.com/downloads/nationalities/nationalities.txt"
download.file(fileUrl, destfile= "./nationalities.txt", method = "curl")

## Then I copied nationalities.txt to one column in Excel and saved the xlsx file. It
# contains 193 rows (or labels for 193 different nationalities).

## Loading xlsx package. If you do not have it installed, first type install.packages("xlsx").

library(xlsx)

## Reading the xlsx file and saving it as an object in R called "labelsNAtion":

labelsNation <- read.xlsx("./nationalities.xlsx", sheetIndex = 1, header = FALSE)

## Replacing numbers for nationality labels in the second column of df:

df$nationality <- factor(df$nationality, levels=c(1:193), labels = labelsNation[,1])