【问题标题】:How to change factor values [duplicate]如何更改因子值[重复]
【发布时间】:2020-05-05 19:59:35
【问题描述】:

我的数据框有 3 个因子变量,它们的值是:

"It was less than adequate for household needs", 
"It was just adequate for household needs", 
"It was more than adequate for household needs"

我需要它们分别为“1”、“2”和“3”。

【问题讨论】:

标签: r


【解决方案1】:

你可以这样做:

df <- data.frame(col=c("It was less than adequate for household needs", 
                       "It was just adequate for household needs",
                       "It was more than adequate for household needs"))

# suggested by @akrun (maintains the order)
df$col <- as.integer(factor(df$col, levels = unique(df$col)))

  col
1   1
2   2
3   3

如果你想保持顺序,可能只是添加一个带有序列的新列:

df$code <- seq(nrow(df))

                                            col code
1 It was less than adequate for household needs    1
2      It was just adequate for household needs    2
3 It was more than adequate for household needs    3

【讨论】:

  • 或使用as.integer(factor(df$col, levels = unique(df$col)))
【解决方案2】:

使用@YOLO 回答中的数据框:

> df$col <- factor(df$col, levels = levels(df$col), labels = 1:3)
> df
  col
1   2
2   1
3   3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多