“应用"功能中的行/列计数器 [英] Row/column counter in 'apply' functions

查看:90
本文介绍了“应用"功能中的行/列计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要apply一个函数,即到矩阵的每一行,又想将该行的编号用作该函数的自变量,该怎么办?例如,假设您要获取矩阵每一行中数字的第n个根,其中n是行号.除了将行号按列绑定到初始矩阵之外,还有别的方法(仅使用apply)吗?

What if one wants to apply a functon i.e. to each row of a matrix, but also wants to use as an argument for this function the number of that row. As an example, suppose you wanted to get the n-th root of the numbers in each row of a matrix, where n is the row number. Is there another way (using apply only) than column-binding the row numbers to the initial matrix, like this?

test <- data.frame(x=c(26,21,20),y=c(34,29,28))

t(apply(cbind(as.numeric(rownames(test)),test),1,function(x) x[2:3]^(1/x[1])))

P.S.实际上,如果 test 实际上是一个矩阵:test <- matrix(c(26,21,20,34,29,28),nrow=3),则行名(test)对:( 谢谢.

P.S. Actually if test was really a matrix : test <- matrix(c(26,21,20,34,29,28),nrow=3) , rownames(test) doesn't help :( Thank you.

推荐答案

我通常要做的是在行号1:nrow(test)而不是test上运行sapply,并在函数内部使用test[i,]:

What I usually do is to run sapply on the row numbers 1:nrow(test) instead of test, and use test[i,] inside the function:

t(sapply(1:nrow(test), function(i) test[i,]^(1/i)))

我不确定这是否真的有效.

I am not sure this is really efficient, though.

这篇关于“应用"功能中的行/列计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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