R:如何在不声明的情况下通过数组符号对列表进行子集化? [英] R: How can I subset a list via array notation without declaring it?

查看:50
本文介绍了R:如何在不声明的情况下通过数组符号对列表进行子集化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我所追求的例子,假设我想要数字列表中3的每一个从1到100的倍数.我知道这样做的更简单方法如下:

As an example of what I'm after, suppose that I want every multiple of 3 in the list of numbers from 1 to 100. The easier way that I know of doing this is as follows:

all<-1:100  
mod3<-all[all%%3==0]

有没有第一行的方法吗?我必须声明一个列表(并因此给它起一个名字),然后才能对其进行子集化,这似乎很愚蠢.我可以调用 subset 函数,但是第二行中的数组表示法很自然,以至于不使用它会很可惜.在理想的世界中,我会称呼类似 1:100 [1:100 %% 3 == 0] 的代码,但这显然会带来错误.仅提及R内置的内容,我有哪些选择?

Is there a way to do this without the first line? It seems silly that I have to declare a list (and therefore give it a name) before I can subset it. I could call the subset function, but the array notation in my second line comes so naturally that it would be a shame to not use it. In an ideal world, I'd call something like 1:100[1:100%%3==0] but that obviously gives errors. Referring only to things that are built-in to R, what are my options?

推荐答案

我们可以将其包装在方括号中,以使其成为一个独立的块,因为不同的运算符具有优先权

We could wrap within brackets to make it a self-contained block as there is precedence for different operators

(1:100)[(1:100)%%3==0]


如果选中?Syntax ,则会给出不同的运算符优先级


If the check the ?Syntax, the different operator precedence are given

#:: ::: access variables in a namespace
#$ @    component / slot extraction
#[ [[   indexing
#^  exponentiation (right to left)
#- +    unary minus and plus
#:  sequence operator
#%any%  special operators (including %% and %/%)
#* /    multiply, divide
#...

在上述情况下, [] 中的表达式可以按预期工作,因为:位于优先于 %% 的优先级之上.但是,这是一个外部问题,因为与:

In the above case, the expression within the [] works as expected because the : is above on the precedence wrt to %%. But, it is the one outside having an issue because [ is higher when compared to :

这篇关于R:如何在不声明的情况下通过数组符号对列表进行子集化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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