r - 如何替换数据框中某列的多个值?

标签 r

我有一个包含多列的数据框,以下是其中一列的示例:

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/

相关文章:

r - 用 R 表示水平和垂直误差线的椭圆

java - gamm() 函数在 JRI 中失败

r - 在R中的data.table上撤消setkey()

r - data.table 中的 `by` 和 `.EACHI`

r - doParallel(包)foreach 不适用于 R 中的大迭代

r - 基于 2 列中的值对表进行重复数据删除 + 模糊匹配

r - 错误 : with-readline=yes (default) and headers/lib are not available

r - 按每行中 NA 的数量对数据进行排序

r - 更改 Shiny 的 dateRangeInput 中 "to"的语言

r - 当某些模型的某些组为空时,使用 purrr 的映射按组估计线性回归