【发布时间】: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
我的数据框有 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
你可以这样做:
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)))
使用@YOLO 回答中的数据框:
> df$col <- factor(df$col, levels = levels(df$col), labels = 1:3)
> df
col
1 2
2 1
3 3
【讨论】: