replace string in dataframe

前端 未结 2 437
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 00:04

I\'m trying to replace a certain string in a large data.frame. I just found the following solution but gsub doesn\'t preserve the original data.frame layout. Ho

相关标签:
2条回答
  • 2021-01-06 00:27
    as.data.frame(sapply(test, function(x) gsub("a", "new", x)))
    
    0 讨论(0)
  • 2021-01-06 00:34

    You will want to lapply through your data.frame testing for character or factor entries and then applying gsub appropriately. The result will be a list, but as.data.frame fixes this.

    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"
    
    0 讨论(0)
提交回复
热议问题