R 确定使用*apply函数时正在处理的元素

R 确定使用*apply函数时正在处理的元素,r,R,假设R知道列表的哪个成员、向量的哪个元素、矩阵的哪个行等。它在运行*apply函数时正在处理。是否可以在函数中使用此索引,而无需采取以下解决方法: fruit <- c("Bananas", "Oranges", "Avocados", "Celeries?") sapply(fruit, function(x) paste(x, "are fruit number", which(fruit==x))) fruit我宁愿写 sapply(seq_along(fruit), fu

假设R知道列表的哪个成员、向量的哪个元素、矩阵的哪个行等。它在运行*apply函数时正在处理。是否可以在函数中使用此索引,而无需采取以下解决方法:

fruit <- c("Bananas", "Oranges", "Avocados", "Celeries?")
sapply(fruit, function(x) 
   paste(x, "are fruit number", which(fruit==x)))
fruit我宁愿写

sapply(seq_along(fruit), function(ii) paste(fruit[ii], "are fruit number", ii))

您可以将索引而不是向量传递给sapply

fruit <- c("Bananas", "Oranges", "Avocados", "Celeries?")
sapply(seq_along(fruit), function(x) paste(fruit[x], "are fruit number", x))

fruit也许mapply是一个有用的选择?(不过这里并不需要)


下一次巴普蒂斯克水果以30秒的速度击败水果,名字更短:-)我很失望没有人注意到芹菜不是水果,而是茎。有趣的是,我这么快就浏览了一遍,我的大脑记录为樱桃。
seq_-along()
基本上就是
1:长度(水果)
的缩写吗?这样做的好处是,
seq_沿着
基本的
,因此速度很快。但最终,这不只是使*应用到一个稍微显式的
for
循环中吗?我想我希望从我的便利循环函数中得到太多,而应该尝试矢量化!如果不是那些爱管闲事的孩子,他也会逃脱惩罚的。
seq_-along
也有点健壮,试试
fruit=c();顺时针(水果);1:长度(水果)
。我同意
for
循环是一个有效的选择,在给定的情况下,我更喜欢哪个更清晰。您可以给
水果
属性,并从
应用
(家族)函数中调用它。请参见此处的用法:
fruit <- c("Bananas", "Oranges", "Avocados", "Celeries?")
mapply(paste, fruit, "are fruit number", seq_along(fruit))