[R] how to compute a vector of min values ?
Greg Snow
538280 at gmail.com
Sun Apr 8 00:40:09 CEST 2012
Peter showed how to get the minimums from a list or data frame using
sapply, here is a way to copy your 1440 vectors into a single list
(doing this and keeping your data in a list instead of separate
vectors will make your life easier in general):
my.list <- lapply( 1:1440, function(x) get( sprintf("v%i",x)) )
You can then name the elements of the list, if you want, with something like:
names(my.list) <- sprintf("v%i", 1:1440)
Then if all the vectors are of the same length you can convert this
into a data frame with:
df <- as.data.frame(my.list)
But this is not needed as most of the work can be done with it as a
list (and if they are different lengths then the list is how it should
stay).
Either way you can now use sapply on the list/data frame to get all
the minimums.
To anticipate a possible future question, if you next want the minimum
of each position across vectors then you can use the pmin function:
do.call( pmin, my.list )
On Fri, Apr 6, 2012 at 12:29 AM, peter dalgaard <pdalgd at gmail.com> wrote:
>
> On Apr 6, 2012, at 00:25 , ikuzar wrote:
>
>> Hi,
>>
>> I'd like to know how to get a vector of min value from many vectors without
>> making a loop. For example :
>>
>>> v1 = c( 1, 2, 3)
>>> v2 = c( 2, 3, 4)
>>> v3 = c(3, 4, 5)
>>> df = data.frame(v1, v2, v3)
>>> df
>> v1 v2 v3
>> 1 1 2 3
>> 2 2 3 4
>> 3 3 4 5
>>> min_vect = min(df)
>>> min_vect
>> [1] 1
>>
>> I 'd like to get min_vect = (1, 2, 3), where 1 is the min of v1, 2 is the
>> min of v2 and 3 is the min of v3.
>>
>> The example above are very easy but, in real, I have got v1, v2, ... v1440
>
> sapply(df, min)
>
> (possibly sapply(df, min, na.rm=TRUE) )
>
>>
>> Thanks for your help,
>>
>> ikuzar
>>
>> --
>> View this message in context: http://r.789695.n4.nabble.com/how-to-compute-a-vector-of-min-values-tp4536224p4536224.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.
>
> --
> Peter Dalgaard, Professor,
> Center for Statistics, Copenhagen Business School
> Solbjerg Plads 3, 2000 Frederiksberg, Denmark
> Phone: (+45)38153501
> Email: pd.mes at cbs.dk Priv: PDalgd at gmail.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.
--
Gregory (Greg) L. Snow Ph.D.
538280 at gmail.com
More information about the R-help
mailing list