2013-05-14 140 views
5

我试图替换大型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) 

THX

回答

14

您将要lapply通过您data.frame测试characterfactor条目,然后适当地应用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" 
+0

你为什么用括号包装整个表达式? – 2014-01-29 09:18:36

+3

@RichardSmith这使得表达式将其结果可视地返回到控制台。分配通常是不可见的。 – James 2014-01-29 09:58:55

6
as.data.frame(sapply(test, function(x) gsub("a", "new", x))) 
+0

感谢,但是这给了我一个汉字字模,我DF具有数值过,然后我遇到问题处理数据进一步 – rainer 2013-05-14 10:13:30

+1

我只是你的榜样工作时。 – Thomas 2013-05-14 11:25:27