如何更改因子值

时间:2020-01-19 17:31:52

标签: r

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

wrapper

我需要将它们分别设置为“ 1”,“ 2”和“ 3”。

2 个答案:

答案 0 :(得分:0)

您可以轻松地做到:

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

答案 1 :(得分:-2)

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

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