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

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

问题描述

如果想要应用一个函数,即矩阵的每一行,但又想使用该行的编号作为该函数的参数,该怎么办.例如,假设您想获得矩阵每一行中数字的第 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])))

附言实际上,如果 test 真的是一个矩阵: test <- matrix(c(26,21,20,34,29,28),nrow=3) , rownames(测试)没有帮助:(谢谢.

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) 上运行 sapply 代替test,并在函数内部使用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天全站免登陆