【问题标题】:Replace multiple numbers at once in data.frame R在data.frame R中一次替换多个数字
【发布时间】:2014-10-05 12:11:12
【问题描述】:

我有一个如下所示的数据框:

   C1 C2
   0   1
   2  -1
   1   1
   -1  2
   0   0

我想将所有 -1 替换为 'minus' , 0 替换为 'nc' , 1 替换为 'plus1' , 2 替换为 'plus2' 。 我知道如何使用 'gsub' 一个一个地替换数字,但我不知道如何一次全部替换它们。 作为 0 和 -1 的示例,这是我的代码:

  gsub(df, '0', 'nc');gsub(df, '-1', 'minus')

提前致谢,

【问题讨论】:

  • 您发布的 gsub 代码似乎根本无效
  • 但是当我分别对它们每个使用它时它就可以工作!
  • 不。 pattern 应该是第一个参数。另外,你不能在整个 df 上运行 gsub,你只能在每列中运行,像 df[] <- lapply(df, gsub, pattern = '0', replacement = 'nc') 这样的东西会为你做第一个替换
  • 对不起,我在我的代码中定义了模式替换和 x,如下所示:gsub(x=df, pattern='0',replacement='nc) 但没有 lapply 它有效!跨度>
  • 那个代码给了我"c(nc, 2, 1, -1, nc)" "c(1, -1, 1, 2, nc)"

标签: r replace dataframe gsub


【解决方案1】:

可能是这样的吗?在这里,我基本上创建了一个“图例”,然后在整个数据框上使用 match 以替换所有列中的值

temp <- data.frame(A = (-1:2), B = c('minus', 'nc', 'plus1', 'plus2'))
df[] <- lapply(df, function(x) temp[match(x, temp$A), "B"])
df
#      C1    C2
# 1    nc plus1
# 2 plus2 minus
# 3 plus1 plus1
# 4 minus plus2
# 5    nc    nc

【讨论】:

    【解决方案2】:

    这里不需要使用正则表达式。在此处的一个简单循环中进行矩阵子设置和替换。请注意,对于替换,通常使用 for 循环比使用 xxxpply 系列函数更好。

    from <-  -1:2 
    to <- c('minus', 'nc', 'plus1', 'plus2')
    for (i in seq_along(from))df[df==from[i]] <- to[i]
    
       C1    C2
    1    nc plus1
    2 plus2 minus
    3 plus1 plus1
    4 minus plus2
    5    nc    nc
    

    【讨论】:

      【解决方案3】:

      如果您没有任何其他值,除了为转换指定的值,这也有效

       lvls <- c('minus', 'nc', 'plus1', 'plus2') #create a vector for specifying the levels of factor.
      

      将每一列转换为factor,并将labels 指定为lvls,如果需要character 列,则将其重新转换回字符

       df[] <- lapply(df, function(x) as.character(factor(x, labels=lvls)))
      
       df
       #     C1    C2
       #1    nc plus1
       #2 plus2 minus
       #3 plus1 plus1
       #4 minus plus2
       #5    nc    nc
      

      更新

      此外,如果您想要带有 gsub 的选项,qdap 中的 mgsub 将采用 vectors 作为搜索词和替换词。

      library(qdap)
      pat <- -1:2
      replacer <- c('minus', 'nc', 'plus1', 'plus2')
      v1 <- mgsub(pat, replacer, as.matrix(df)) #on the original dataset
      dim(v1) <- dim(df)
      df[] <- v1
       df
       #    C1    C2
       #1    nc plus1
       #2 plus2 minus
       #3 plus1 plus1
       #4 minus plus2
       #5    nc    nc
      

      数据

      df <- structure(list(C1 = c(0L, 2L, 1L, -1L, 0L), C2 = c(1L, -1L, 1L, 
      2L, 0L)), .Names = c("C1", "C2"), class = "data.frame", row.names = c(NA, 
      -5L))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        • 2013-05-10
        • 2021-04-06
        • 1970-01-01
        • 2019-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多