【问题标题】:replace string in dataframe替换数据框中的字符串
【发布时间】:2013-05-08 13:32:43
【问题描述】:

我正在尝试替换大型 data.frame 中的某个字符串。我刚刚找到了以下解决方案,但 gsub 不保留原始 data.frame 布局。我怎样才能做到这一点。

我的意思是我想替换一个字符串,不想改变df的布局。

考虑这个例子:

test<-data.frame(a=c("a","b","c","d"),b=c("a","e","g","h"),c=c("i","j","k","a"))
gsub("a","new",test)

谢谢

【问题讨论】:

    标签: r replace dataframe gsub


    【解决方案1】:

    您将希望通过data.frame 测试characterfactor 条目来lapply,然后适当地应用gsub。结果将是list,但as.data.frame 解决了这个问题。

    test$val <- 1:4 # a non character/factor variable
    (test2 <- as.data.frame(lapply(test,function(x) if(is.character(x)|is.factor(x)) gsub("a","new",x) else x)))
        a   b   c val
    1 new new   i   1
    2   b   e   j   2
    3   c   g   k   3
    4   d   h new   4
    class(test2$val) # to see if it is unchanged
    [1] "integer"
    

    【讨论】:

    • 你为什么要把整个表达式括在括号里?
    • @RichardSmith 这使得表达式将其结果明显地返回到控制台。作业通常以不可见的方式返回。
    【解决方案2】:
    as.data.frame(sapply(test, function(x) gsub("a", "new", x)))
    

    【讨论】:

    • 谢谢,但这给了我一个字符矩阵,我的 df 也有数值,然后在进一步处理数据时遇到问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2021-12-14
    • 2021-09-07
    • 2021-04-26
    • 2022-11-12
    相关资源
    最近更新 更多