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

查看:47
本文介绍了如何将函数应用于 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天全站免登陆