在列中仅替换“0”(单个零),而不用更大的数字替换零(例如10,20,30等)

时间:2014-03-19 14:52:40

标签: r replace gsub

我想让我的数据框中的任何0值都有一个正数,这样我的模型才能工作。

但是,当我尝试替换所有零值时,我还会替换属于更大数字的字符串中的零,例如10,20,30,40 ...... 100,1000等。

如何指定我只想替换那些实际为零的值,而不是只包含任何包含数字零的字符串?

谢谢!

以下是代码:

total<- read.csv("total.csv")    
total.rm <- na.omit(total)

#removing NAs/NAN
total.rm$mediansp[which(is.nan(total.rm$mediansp))] = NA
total.rm$mediansp[which(total.rm$mediansp==Inf)] = NA
total.rm$connections[which(is.nan(total.rm$connections))] = NA
total.rm$connections[which(total.rm$connections==Inf)] = NA

#make all 0 values positive
total.rm$mediansp <- gsub("0", "0.00001", total.rm$mediansp)
total.rm$connections <- gsub("0", "0.00001", total.rm$connections)

#remove zeros varaibles
total.rm$mediansp <- gsub("NA", "0", total.rm$mediansp)
total.rm$connections <- gsub("NA", "0", total.rm$connections)
total.rm$mediansp <- gsub("0", "0.01", total.rm$mediansp)
total.rm$connections <- gsub("0", "0.01", total.rm$connections)

#convert character variables to numeric variables  
total.rm$mediansp <- as.numeric(total.rm$mediansp) 
total.rm$connections <- as.numeric(total.rm$connections)

#plot maps with fitted values and with residuals
sc.lm <- lm (log(mediansp) ~ log(connections), total.rm, na.action="na.exclude")
total.rm$fitted.s <- predict(sc.lm, total.rm) - mean(predict(sc.lm, total.rm))
total.rm$residuals <- residuals(sc.lm)

这是结构:

data.frame':    133537 obs. of  19 variables:
$ pcd           : Factor w/ 1736958 levels "AB101AA","AB101AB",..: 
$ pcdstatus     : Factor w/ 5 levels "Insufficient Data",..: 5 5 5 5 5 5 5 5 5 5 ...
$ mbps2         : num  0 0 0 0 1 0 1 1 0 0 ...
$ averagesp     : chr  "16" "19.3" "14.1" "14.9" ...
$ mediansp      : chr  "16.2" "20" "18.7" "16.8" ...
$ maxsp         : chr  "23.8" "24" "20.2" "19.7" ...
$ nga           : num  0 0 0 1 0 1 1 1 1 1 ...
$ connections   : chr  "54" "14" "98" "43" ...
$ oslaua        : Factor w/ 407 levels "","95A","95B",..: 326 326 326 326 326 326 326 
$ x             : int  540194 540194 540300 539958 540311 539894 540311 540379 540310 
$ y             : int  169201 169201 169607 169584 168997 169713 168997 168749 168879 
$ ctry          : Factor w/ 4 levels "E92000001","N92000002",..: 1 1 1 1 1 1 1 1 1 1 
$ hro2          : Factor w/ 13 levels "","E12000001",..: 8 8 8 8 8 8 8 8 8 8 ...
$ soa2          : Factor w/ 7197 levels "","E02000001",..: 145 145 135 135 145 135 145 
$ urindew       : int  5 5 5 5 5 5 5 5 5 5 ...
$ averagesp.lt  : num  2.77 2.96 2.65 2.7 2.05 ...
$ mediansp.lt   : num  2.79 3 2.93 2.82 2.09 ...
$ maxsp.lt      : num  3.17 3.18 3.01 2.98 2.68 ...
$ connections.lt: num  3.99 2.64 4.58 3.76 3.22 ...

1 个答案:

答案 0 :(得分:1)

gsub正在下面的代码中进行正则表达式替换。要仅替换字符串"0",请在gsub pattern = "^0$"中创建模式参数。这应该可以解决你的问题。

作为补充说明,简单地用非常小的数字替换0来形成模型几乎肯定是不好的形式。选择一个更好的模型。