找出两个向量的所有值之间的差异 [英] Find the difference between all values of two vectors

查看:69
本文介绍了找出两个向量的所有值之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出多对数字之间的差异.

I am trying to find the difference between many pairs of numbers.

这些数字位于两个长度不等的向量中.例如,

These numbers are in two vectors of unequal length. For example,

    a<- c(1:5)
    b<- c(1:10)

现在,我需要某种方法来计算 a[[1]] - b 然后 a[[2]] - b 等等,直到 a[[5]] - b.这些计算中的每一个都应该产生一个向量,长度为 10 个数字.

Now, I need some way of calculating the a[[1]] - b and then a[[2]] - b and so on until a[[5]] - b. Each of these calculations should result in a vector, 10 numbers long.

这些差异向量中的每一个都应作为数据帧中的列一起存储.第一列应该是减去'b'的位置,随后的列应该以'a'的位置为标题(所以有5列和10行).

Each of these vectors of differences should be stored together as columns in a dataframe. The first column should be the position of ´b´ subtracted and the subsequent columns should be titled with the position of ´a´ (so there are 5 columns and 10 rows).

         a[1] a[2] ... a[5]
    b[1]
    b[2]
    ...
    b[10]

我对在 R 中编写函数非常陌生.我对使用 *apply 函数组也很陌生.我一直在尝试结合我所学到的关于编写函数的知识和 *apply 函数组来解决这个问题,但它还没有发生.感谢您的帮助!

I am very new to writing functions in R. I am also new to using the *apply group of functions. I have been trying to combine what I have learned about writing functions and the *apply group of functions to solve this but it just isn´t happening yet. Thank you for your help!

附言抱歉,如果之前已经问过这个问题.我搜索但找不到答案.

P.S. Sorry if this has been asked before. I searched but could not find the answer.

推荐答案

sapply(a, "-", b)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    2    3    4
# [2,]   -1    0    1    2    3
# [3,]   -2   -1    0    1    2
# [4,]   -3   -2   -1    0    1
# [5,]   -4   -3   -2   -1    0
# [6,]   -5   -4   -3   -2   -1
# [7,]   -6   -5   -4   -3   -2
# [8,]   -7   -6   -5   -4   -3
# [9,]   -8   -7   -6   -5   -4
#[10,]   -9   -8   -7   -6   -5

<小时>

说明

利用标量减去 R 中的向量是所述标量与向量的每个元素之间的元素减法这一事实,我们可以简单地将减号 - 运算符应用于每个值在 a 中针对整个向量 b.


Explanation

Taking advantage of the fact that a scalar minus a vector in R is an element-wise subtraction between said scalar and each element of the vector, we can simply apply the minus - operator to each value in a against the whole vector b.

这篇关于找出两个向量的所有值之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆