将函数应用于矩阵或数据框的每一行 [英] Apply a function to every row of a matrix or a data frame

查看:100
本文介绍了将函数应用于矩阵或数据框的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个n乘2的矩阵和一个将2向量作为其参数之一的函数。我想将这个函数应用到矩阵的每一行并得到一个n向量。如何在R中做到这一点?



例如,我想计算三点上2D标准正态分布的密度:
(0,0),mu = c(0,0),sigma = c(1,1),ρ0 = 0(0,0),b 0 = b(pre $ p $ bivariate.density ){
exp(-1 /(2 *(1-rho ^ 2))*(x [1] ^ 2 / sigma [1] ^ 2 + x [2] ^ 2 / sigma [2] ^ 2-2 * rho * x [1] * x [2] /(sigma [1] * sigma [2])))* 1 /(2 * pi * sigma [1] * sigma [2] * sqrt (1,2),c(3,4),c(5,6))
(b,b)

如何将函数应用于 out



如何以指定的方式将除点之外的其他参数的值传递给函数?

解决方案

您只需使用 apply()函数:

  R> M<  - 矩阵(1:6,nrow = 3,byrow = TRUE)
R> M
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
R> (M,1,function(x)2 * x [1] + x [2])
[1] 4 10 16
R>

这需要一个矩阵并将一个(愚蠢的)函数应用于每一行。您将额外的参数作为第四,第五,...参数传递给 apply()


Suppose I have a n by 2 matrix and a function that takes a 2-vector as one of its arguments. I would like to apply the function to each row of the matrix and get a n-vector. How to do this in R?

For example, I would like to compute the density of a 2D standard Normal distribution on three points:

bivariate.density(x = c(0, 0), mu = c(0, 0), sigma = c(1, 1), rho = 0){
    exp(-1/(2*(1-rho^2))*(x[1]^2/sigma[1]^2+x[2]^2/sigma[2]^2-2*rho*x[1]*x[2]/(sigma[1]*sigma[2]))) * 1/(2*pi*sigma[1]*sigma[2]*sqrt(1-rho^2))
}

out <- rbind(c(1, 2), c(3, 4), c(5, 6))

How to apply the function to each row of out?

How to pass values for the other arguments besides the points to the function in the way you specify?

解决方案

You simply use the apply() function:

R> M <- matrix(1:6, nrow=3, byrow=TRUE)
R> M
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
R> apply(M, 1, function(x) 2*x[1]+x[2])
[1]  4 10 16
R> 

This takes a matrix and applies a (silly) function to each row. You pass extra arguments to the function as fourth, fifth, ... arguments to apply().

这篇关于将函数应用于矩阵或数据框的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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