R:基于索引的应用于向量

Posted

技术标签:

【中文标题】R:基于索引的应用于向量【英文标题】:R: index-based apply to vector 【发布时间】:2021-12-20 05:31:55 【问题描述】:

给定:

original_vector <- c(2, 2, 2, 3)
indices <- c(1, 0, 0, 1)

我想对original_vector 应用一些函数,但基于indices。例如如果函数是“以 5 为增量”,我想要的输出是 [7, 2, 2, 8]

我知道如何使用 for 循环来做到这一点,但我想使用 apply 系列中的一些东西。

有类似的问题,但似乎比我自己的用例复杂。

【问题讨论】:

你只有一个向量还是想在列表或数据框中做? 【参考方案1】:

如果您想使用 apply 系列中的某些东西,请考虑使用 mapply 并提供两个向量。 mapply 和自定义函数 my_fun 采用两个参数:original_vectorindices

my_fun <- function(vec, indices) 
  vec[indices == 1] <- vec[indices == 1] + 5
  vec


mapply(my_fun, original_vector, indices)

输出

[1] 7 2 2 8

【讨论】:

【参考方案2】:

dplyr 你可以这样做:

library(dplyr)
data.frame(original_vector, indices) %>%
  mutate(original_vector = ifelse(indices > 0,
                                  original_vector + 5,
                                  original_vector))
  original_vector indices
1               7       1
2               2       0
3               2       0
4               8       1

【讨论】:

以上是关于R:基于索引的应用于向量的主要内容,如果未能解决你的问题,请参考以下文章

是否有用于查找向量中元素索引的 R 函数?

r 向量相交和返回索引

R:向向量的某些索引添加值

在R中的排序向量中获取索引的最有效方法?

如何使用 R 在向量中找到第二个非连续出现的值的索引?

使用向量来索引 R 中的 data.frame