【问题标题】:R - Replacing levels of a factor using another vectorR - 使用另一个向量替换因子的水平
【发布时间】:2016-02-14 19:30:53
【问题描述】:

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

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

但它不起作用:(

请帮忙。提前致谢!

【问题讨论】:

  • 你可以试试factor(labels[nationality])
  • 我试过了,但是没有用。还有什么想法吗??
  • 为您的问题和所需输出提供一个可重现的小示例。请参阅here 了解如何创建它
  • set.seed(1); a &lt;- sample(1:10); b &lt;- letters[1:10]; factor(a,labels=b) 给出[1] c d e g b h i f j a。你在寻找这样的东西吗?

标签: r r-factor


【解决方案1】:

我做到了!但我不得不采取中间步骤,将带有 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])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-04
    • 2020-11-13
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多