冒号运算符因素:列表

时间:2016-08-06 20:33:09

标签: r

如果f1和f2是整数, 我知道f1:f2表示从a到b的整数列表,差异为1.在a和b都是因子的情况下,f1:f2表示一个新因子,其中f1和f2的因子水平的每个唯一组合的水平(互动)如下所示。 如果我使用f1:x,其中x是与某个因子相对的列表,该怎么办?

f1<-gl(2,3) #create factor with 2 levels 
f2<-gl(3,2) #create factor with 3 levels 
x<-rnorm(6) #create list with 6 real numbers(sampled from normal)

> f1
[1] 1 1 1 2 2 2
Levels: 1 2

> f2
[1] 1 1 2 2 3 3
Levels: 1 2 3

> x
[1]  0.6705013 -0.2116773 -0.3812724 -0.3687866  1.4878815  0.3095373

f1:f2

[1] 1:1 1:1 1:2 2:2 2:3 2:3
Levels: 1:1 1:2 1:3 2:1 2:2 2:3

f1:x

[1] 1
Warning messages:
1: In f1:x : numerical expression has 6 elements: only the first used
2: In f1:x : numerical expression has 6 elements: only the first used

正如您所看到的,我得到一个带有警告消息的输出1。 发生了什么事?

1 个答案:

答案 0 :(得分:0)

一些实验表明,R将冒号两侧的表达式强制转换为数字,取每个表达式的第一个元素,然后使用冒号seq(from, to)评估表达式。 E.g。

> factor(c("C","B","A")):(7:8)
[1] 3 4 5 6 7

在您的示例中,1: 0.6705013评估为1

相关问题