如何将函数应用于R中向量的每个元素 [英] How to apply a function to each element of a vector in R

查看:230
本文介绍了如何将函数应用于R中向量的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想将向量的每个偶数元素乘以2,并将向量的每个奇数元素乘以3.下面的代码可以做到这一点:

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:

v <- 0:10

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

如果我有两个以上的案件,这将变得困难.似乎apply系列函数从不处理向量,因此我不知道解决此问题的更好方法.如果我对数据进行了转换,也许使用apply函数可能会起作用,但似乎不应该为了解决这个简单的问题而使用该功能.

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()是不可能的,我认为sapply()仅适用于列表.

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.

推荐答案

最简单的方法是:

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

文档中要搜索的术语是参数回收" ... R语言的功能.仅适用于二进位缀功能(请参见?Ops).对于不会因某些参数而出错并且不能依赖于"v"的结构是如此规则的非二元矢量化函数,可以使用ifelse:

The term to search for in the documentation is "argument recycling" ... a feature of the R language. Only works for dyadic infix functions (see ?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:

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

这篇关于如何将函数应用于R中向量的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆