replace string in dataframe

爷,独闯天下 提交于 2019-11-30 20:56:24

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"
Thomas
as.data.frame(sapply(test, function(x) gsub("a", "new", x)))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!