我有一个包含多列的数据框,以下是其中一列的示例:
df <- data.frame(x=1:3)
数字1代表"is",2代表“否”,3代表“也许”。 我想出的一种解决方案是更改变量的类,然后使用:
df$x <- replace(df$x, "1", "Yes")
并重复“不”和“也许”。
然而其中一列有 27 个不同的值,代表 27 个不同的单词,这样代码就太大了。
关于如何有效地用单词替换数字有什么想法吗?
最佳答案
您可以使用 plyr
中的 mapvalues()
:
library(plyr)
x <- c("a", "b", "c")
mapvalues(x, c("a", "c"), c("A", "C"))
[1] "A" "b" "C"
就您而言,
df <- data.frame(x=1:3)
mapvalues(df$x, c(1,3,2), c("Yes","Maybe","No"))
[1] "Yes" "No" "Maybe"
由于 plyr
已停用,您无需使用以下代码调用包即可完成此操作(直接从 body(mapvalues)
复制)。
my_mapvalues <- function(x, from, to, warn_missing = TRUE) {
if (length(from) != length(to)) {
stop("`from` and `to` vectors are not the same length.")
}
if (!is.atomic(x)) {
stop("`x` must be an atomic vector.")
}
if (is.factor(x)) {
levels(x) <- mapvalues(levels(x), from, to, warn_missing)
return(x)
}
mapidx <- match(x, from)
mapidxNA <- is.na(mapidx)
from_found <- sort(unique(mapidx))
if (warn_missing && length(from_found) != length(from)) {
message("The following `from` values were not present in `x`: ",
paste(from[!(1:length(from) %in% from_found)], collapse = ", "))
}
x[!mapidxNA] <- to[mapidx[!mapidxNA]]
x
}
关于r - 如何替换数据框中某列的多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73834365/