在ifelse中索引或应用

时间:2018-01-20 17:41:03

标签: r

搜索许多地方,我找不到任何关于在使用ifelse或apply时如何利用项目索引的指示。 举一个简单的例子,如果我想通过索引将向量中的值除,我可以在for循环中进行:

for( i in 1:length(vector) ){ vector[i] = vector[i] / i }

是否有一些内部变量可以在ifelse或apply语句中使用? 例如:vector = ifelse( is.finite(vector), vector/internal.index.variable, vector )关于向量和矩阵?

感谢, 汤姆

2 个答案:

答案 0 :(得分:1)

seq_along(x)是你的朋友;它创建一个等于1:length(x)的整数向量:

vec <- vec2 <-  c(5, Inf, 7) # Need two copies to modify one in the loop


# Your for loop example
for ( i in 1:length(vec) ) {
    vec2[i] <- vec2[i] / i
}

vec2
# [1] 5.000000      Inf 2.333333

# Accomplish the same thing with apply()
sapply(vec, '/', seq_along(vec))
# [1] 5.000000      Inf 2.333333

# Accomplish the same thing with ifelse()
ifelse(is.finite(vec), vec / seq_along(vec), vec)
# [1] 5.000000      Inf 2.333333

答案 1 :(得分:0)

a <- c(1,2,Inf)
a / seq_along(a)

由指数划分的无限仍然是无穷大。因此,无论如何,无限元素保持不变。

相关问题