简体   繁体   English

如何将函数应用于R中向量的每个元素

[英]How to apply a function to each element of a vector in R

Let's say I want to multiply each even element of a vector by 2 and each odd element of a vector by 3. Here is some code that can do this: 假设我想将向量的每个偶数元素乘以2,将向量的每个奇数元素乘以3.以下是一些可以执行此操作的代码:

v <- 0:10

idx <- v %% 2 == 0
v[idx] <- v[idx] * 2
v[!idx] <- v[!idx] * 3

This would get difficult if I had more than two cases. 如果我有两个以上的案例,这将变得困难。 It seems like the apply family of functions never deals with vectors so I don't know a better way to do this problem. 看起来应用函数系列从不处理向量,所以我不知道更好的方法来解决这个问题。 Maybe using an apply function would work if I made transformations on the data, but it seems like that shouldn't be something that I would need to do to solve this simple problem. 如果我对数据进行了转换,那么使用apply函数可能会有效,但似乎不应该是我需要做的事情来解决这个简单的问题。

Any ideas? 有任何想法吗?

Edit: Sorry for the confusion. 编辑:抱歉混乱。 I am not specifically interested in the "%%" operator. 我对“%%”运算符并不特别感兴趣。 I wanted to put some concrete code in my question, but, based on the responses to the question, was too specific. 我想在我的问题中提出一些具体的代码,但是,根据对问题的回答,这个代码太具体了。 I wanted to figure out how to apply some arbitrary function to each member of the list. 我想弄清楚如何将一些任意函数应用于列表的每个成员。 This was not possible with apply() and I thought sapply() only worked with lists. 使用apply()是不可能的,我认为sapply()只适用于列表。

You can do: 你可以做:

v <- v * c(2, 3)[v %% 2 + 1]

It is generalizable to any v %% n , eg: 它可以推广到任何v %% n ,例如:

v <- v * c(2, 3, 9, 1)[v %% 4 + 1]

Also it does not require that length(v) be a multiple of n . 此外,它不要求length(v)n的倍数。

You can use vector multiplication to do what you want: 您可以使用矢量乘法来执行您想要的操作:

tmp <- 1:10
tmp * rep(c(3,2), length(tmp)/2)

This is easy to extend to three or more cases: 这很容易扩展到三种或更多种情况:

tmp * rep(c(3,2,4), length(tmp)/3)

Easiest would be: 最容易的是:

v*c(2,3) # as suggested by flodel in a comment.

The term to search for in the documentation is "argument recycling" ... a feature of the R language. 在文档中搜索的术语是“参数回收”...... R语言的一个特性。 Only works for dyadic infix functions (see ?Ops ). 仅适用于二元中缀函数(请参阅?Ops )。 For non-dyadcic vectorized functions that would not error out with some of the arguments and where you couldn't depend on the structure of "v" to be quite so regular, you could use ifelse: 对于非dyadcic矢量化函数,它们不会因某些参数而出错,而且你不能依赖于“v”的结构,那么你可以使用ifelse:

ifelse( (1:length(v)) %% 2 == 0, func1(v), func2(v) )

This constructs two vectors and then chooses elements in the first or second based on the truth value of hte first argument. 这构造了两个向量,然后根据第一个参数的真值选择第一个或第二个中的元素。 If you were trying to answer the question in the title of your posting then you should look at: 如果您试图回答帖子标题中的问题,那么您应该看看:

?sapply

Here is an answer allowing any set of arbitrary functions to be applied to defined groups within a vector. 这是一个答案,允许任何一组任意函数应用于向量中的已定义组。

# source data
test <- 1:9
# categorisations of source data
cattest <- rep(1:3,each=3)
#[1] 1 1 1 2 2 2 3 3 3

Make the function to differentially apply functions: 使功能差异化应用功能:

categ <- function(x,catg) {
          mapply(
                 function(a,b) {
                                switch(b,
                                       a * 2,
                                       a * 3,
                                       a / 2
                                      )
                               },
                  x,
                  catg
                 )
         }
# where cattest = 1, multiply by 2
# where cattest = 2, multiply by 3
# where cattest = 3, divide by 2

The result: 结果:

categ(test,cattest)
#[1]  2.0  4.0  6.0 12.0 15.0 18.0  3.5  4.0  4.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "如何在 R 中使用 apply 将字符串粘贴到字符串向量的每个元素上?" - How to paste a string on each element of a vector of strings using apply in R? R studio:编写一个 for 循环,将自定义函数应用于输入向量,并为该向量中的每个元素输出一个单独的数据帧 - R studio: Write a for loop to apply a customized function to a vector of inputs, and outputs a separate dataframe for each element in that vector R根据向量中的元素应用功能 - R Apply function depending on element in a vector 如何将 R 向量中每个元素的长度传递给 substr function? - How to pass the length of each element in an R vector to the substr function? 给定一个向量,将一个函数应用于另一个向量的每个元素 - Given a vector, apply a function to each element of another vector 如何将 function 应用于数据集向量的每个元素,然后返回该向量? - How do you apply a function to each element of a dataset vector, and then return that vector? 在R中的数据框的每个元素上应用带有参数的函数 - Apply function with parameters on each element of a dataframe in R R - 在数组的每个元素上并行应用函数 - R - apply function on each element of array in parallel 将 function 应用于嵌套列表的每个元素 r - apply function to each element of a list nested r 将函数应用于R中数据框中的每个元素 - apply function to each element in dataframe in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM