2013-05-14 142 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