R中至少有2个向量[重复]

时间:2021-10-15 22:53:19

Possible Duplicate:
Compute the minimum of a pair of vectors

可能重复:计算一对向量的最小值

I have two vectors of the same length:

我有两个相同长度的向量:

a <- rnorm(40)
b <- rnorm(40)

Now, I want to create a third vector c which has a each point the minor value of a and b. This could be a solution:

现在,我想创建第三个向量c,其中每个点都有a和b的次要值。这可能是一个解决方案:

for (i in 1:40)
{c[i] <- min(a[i],b[i])}

However, I guess there is an easier way to do this.

但是,我想有一种更简单的方法可以做到这一点。

2 个解决方案

#1


8  

This is exactly what pmin is for... which is documented in ?min.

这正是pmin的用途......记录在?min中。

a <- rnorm(40)
b <- rnorm(40)
minab <- pmin(a,b)

#2


4  

Joshua's answer is without doubt the best solution for your question. However, I sometimes personally like to use simple tools and create my own piece of code or function. Here is another way of solving the problem:

毫无疑问,约书亚的回答是你问题的最佳解决方案。但是,我个人有时喜欢使用简单的工具并创建自己的代码或功能。这是解决问题的另一种方法:

apply(data.frame(v1 = rnorm(40), v2 = rnorm(40)),1,min)

#1


8  

This is exactly what pmin is for... which is documented in ?min.

这正是pmin的用途......记录在?min中。

a <- rnorm(40)
b <- rnorm(40)
minab <- pmin(a,b)

#2


4  

Joshua's answer is without doubt the best solution for your question. However, I sometimes personally like to use simple tools and create my own piece of code or function. Here is another way of solving the problem:

毫无疑问,约书亚的回答是你问题的最佳解决方案。但是,我个人有时喜欢使用简单的工具并创建自己的代码或功能。这是解决问题的另一种方法:

apply(data.frame(v1 = rnorm(40), v2 = rnorm(40)),1,min)