[R] Odp: applying a function to data frame columns

Petr PIKAL petr.pikal at precheza.cz
Fri Feb 22 08:41:26 CET 2008


Hi

r-help-bounces at r-project.org napsal dne 21.02.2008 22:57:31:

> 
> useR's,
> 
> I want to apply this function to the columns of a data frame:
> 
> u[u >= range(v)[1] & u <= range(v)[2]]

Do you really mean this function?

range(v) gives you an overall range in data frame v e.g. (1,5)

and u[your ranges]

gives you a vector of all values in u which lie inside the overall range.

If you want to select in each u column values within range of appropriate 
v column and if your data frames are not really huge and have reasonable 
number of columns I would use for cycle.

for( i in 1:dim(u)[2]) z[[i]]<-u[u[,i] >= range(v[,i])[1] & u[,i] <= 
range(v[,i])[2], i]

Regards
Petr


> 
> where u is the n column data frame under consideration and v is a data 
frame
> of values with the same number of columns as u.  For example,
> v1 <- c(1,2,3)
> v2 <- c(3,4,5)
> v3 <- c(2,3,4)
> v <- as.data.frame(cbind(v1,v2,v3))
> 
> uk1 <- seq(min(v1) - .5, max(v1) + .5, .5)
> uk2 <- seq(min(v2) - .5, max(v2) + .5, .5)
> uk3 <- seq(min(v3) - .5, max(v3) + .5, .5)
> 
> u <- do.call("expand.grid", list(uk1,uk2,uk3))
> 
> Here, there are 3 columns; instead of hard-coding this, can the function
> given above, which will restrict the u data frame to values within the
> ranges of each variable, be done with the apply function?  Thanks in
> advance.
> 
> dxc13
> 
> -- 
> View this message in context: 
http://www.nabble.com/applying-a-function-to-
> data-frame-columns-tp15619657p15619657.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list