gpt4 book ai didi

r - 如何在 R 中的数据框中重新编码数据

转载 作者:行者123 更新时间:2023-12-05 08:25:25 26 4
gpt4 key购买 nike

可以推广到多列的数据示例如下

id  colour  zm          cinema  pen     wm          monitor mn
1 blue good a wood bad 24 very good
2 Yellow bad b metal good enough 23 good
3 Red good enough d plastic bad 27 good enough

我要得到下表

id  colour  zm  cinema  pen     wm  monitor mn
1 blue B a wood D 34 A
2 Yellow D b metal C 23 B
3 Red C d plastic D 27 C

非常好= A,好= B,足够好= C,差= D。我知道这可以通过“变异”来完成,但很难在数据框架内完成。

最佳答案

我们可以使用命名向量来改变值

nm1 <- setNames(LETTERS[1:4], c("very good", "good", "good enough", "bad"))
library(dplyr)
df2 <- df1 %>%
mutate(across(c(zm, wm, mn), ~ nm1[.]))

-输出

df2
# id colour zm cinema pen wm monitor mn
#1 1 blue B a wood D 24 A
#2 2 Yellow D b metal C 23 B
#3 3 Red C d plastic D 27 C

数据

df1 <- structure(list(id = 1:3, colour = c("blue", "Yellow", "Red"), 
zm = c("good", "bad", "good enough"), cinema = c("a", "b",
"d"), pen = c("wood", "metal", "plastic"), wm = c("bad",
"good enough", "bad"), monitor = c(24L, 23L, 27L), mn = c("very good",
"good", "good enough")), class = "data.frame", row.names = c(NA,
-3L))

关于r - 如何在 R 中的数据框中重新编码数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65799299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com