本文介绍了括号使向量不同.向量表达式究竟是如何计算的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的数据框:

I have a data frame as follows:

planets               type diameter rotation rings
Mercury Terrestrial planet    0.382    58.64 FALSE 
Venus   Terrestrial planet    0.949  -243.02 FALSE 
Earth   Terrestrial planet    1.000     1.00 FALSE 
Mars    Terrestrial planet    0.532     1.03 FALSE
Jupiter          Gas giant   11.209     0.41 TRUE
Saturn          Gas giant     9.449     0.43 TRUE
Uranus          Gas giant     4.007    -0.72 TRUE
Neptune          Gas giant    3.883     0.67  TRUE

我想选择最后 3 行:

I wanted to select last 3 rows:

planets_df[nrow(planets_df)-3:nrow(planets_df),]

然而,我有一些我没想到的事情:

However, I've got something I didn't expect:

planets          type                  diameter rotation rings
Jupiter          Gas giant            11.209     0.41  TRUE
Mars             Terrestrial planet    0.532     1.03 FALSE
Earth            Terrestrial planet    1.000     1.00 FALSE
Venus            Terrestrial planet    0.949  -243.02 FALSE
Mercury          Terrestrial planet    0.382    58.64 FALSE

通过试错法,我了解到

> (nrow(planets_df)-3):nrow(planets_df)
[1] 5 6 7 8

> nrow(planets_df)-3:nrow(planets_df)
[1] 5 4 3 2 1 0

R 如何准确评估 : 语句(参考方括号)?

How does exactly R evaluate : statement (with reference to brackets)?

推荐答案

冒号运算符将优先于算术运算.最好通过示例进行实验以将逻辑内化:

The colon operator will take precedence over the arithmetic operations. It is always best to experiment with examples to internalize the logic:

2*2:6-1

我们应该期待什么答案?有人会说4 5.想法是它会简化为2*2=46-1=5,因此4:5.

What answer should we expect? Some would say 4 5. The thinking is that it will simplify to 2*2=4 and 6-1=5, therefore 4:5.

2*2:6-1
[1]  3  5  7  9 11

这个答案会让任何没有考虑过操作顺序的人感到惊讶.表达式 2*2:6-1 的简化方式不同.先执行序列2:6,然后是乘法,最后是加法.我们可以把它写成 2 * (2 3 4 5 6),也就是 4 6 8 10 12 减去 1 得到得到 3 5 7 9 11.

This answer will surprise anyone who hasn't considered the order of operations in play. The expression 2*2:6-1 is simplified differently. The sequence 2:6 is carried out first, then the multiplication, and finally the addition. We could write it out as 2 * (2 3 4 5 6), which is 4 6 8 10 12 and subtract 1 from that to get 3 5 7 9 11.

通过用括号分组,我们可以控制运算顺序,就像我们在基本算术中做的类似,以获得我们最初预期的答案.

By grouping with parantheses we can control the order of operations as we would do similarly in basic arithmetic to get the answer that we first expected.

(2*2):(6-1)
[1] 4 5

您可以将此推理应用到您的示例中,以调查 : 运算符看似奇怪的行为.

You can apply this reasoning to your example to investigate the seemingly odd behavior of the : operator.

既然你知道了密码,我们应该对 (2*2):6-1 有什么期待?

Now that you know the secret codes, what should we expect from (2*2):6-1?

这篇关于括号使向量不同.向量表达式究竟是如何计算的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 12:25