[R-sig-Geo] Change dataframe values using log and if condition

Vijay Lulla vijaylulla at gmail.com
Fri Dec 29 21:38:40 CET 2017


Maybe this can be of some help to you.

> set.seed(1234L)
> d <-
data.frame(v1=1:5,v2=c(0,abs(runif(4))),v3=c(runif(3),0,0),v4=0,v5=0.5)
> fn <- function(x) {
+   y <- x
+   y[y==0] <- log1p(y[y==0])
+   y[y>0] <- log(y[y>0])
+   y
+ }
>
> d[,2:5] <- apply(d[,2:5], 2, fn)
>
> d
  v1         v2         v3 v4         v5
1  1  0.0000000 -0.1497591  0 -0.6931472
2  2 -2.1741619 -0.4458019  0 -0.6931472
3  3 -0.4743339 -4.6569103  0 -0.6931472
4  4 -0.4954860  0.0000000  0 -0.6931472
5  5 -0.4725999  0.0000000  0 -0.6931472
>

Thanks,
Vijay.

On Fri, Dec 29, 2017 at 2:51 PM, Daniel Furlan Amaral <dfamaral at usp.br>
wrote:

> Dear all,
>
> I need to calculate log or log1p for all values (rows) in specific
> columns of a data.frame with 5500 rows and 23 columns.
>
> When i > 0, apply log, and when i == 0, apply log1p. So I thought I
> should use a for loop with a ifelse condition, log and log1p
> functions.
>
> I have already tried many possibilities, but none solved. This is
> something I tried, but the data.frame's values didn't change:
>
>
>
> tcPainelLog <- tcPainel; cols <- names(tcPainelLog[6:17])
>
> for (j in cols) {
>     for (i in 1:length(j)) {
>         ifelse(tcPainelLog[[i]] > 0, log(i), log1p(i))
>     }
> }
>
>
>
> I would appreciate any help.
>
> Thank you.
>
> Daniel
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>



-- 
Vijay Lulla, Ph.D.

Assistant Professor,
Dept. of Geography, IUPUI
425 University Blvd, CA-207C.
Indianapolis, IN-46202
vlulla at iupui.edu

<http://vijaylulla.com>
http://vijaylulla.com

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list