如何处理R中的错误“子集数据帧时选择了未定义的列”?
错误“子集数据框时选择了未定义的列”意味着R不能理解子集数据框时要使用的列。通常,当我们忘记在单个方括号内进行子集设置时使用逗号时会发生这种情况。
示例
请看以下数据帧-
> set.seed(99)> x1<-rnorm(20,0.5)
> x2<-rpois(20,2)
> x3<-runif(20,2,10)
> x4<-rnorm(20,0.2)
> x5<-rpois(20,5)
> df<-data.frame(x1,x2,x3,x4,x5)
> df
x1 x2 x3 x4 x5
1 0.7139625 4 9.321058 0.33297863 4
2 0.9796581 2 4.298837 -1.47926432 11
3 0.5878287 3 7.389898 -0.07847958 5
4 0.9438585 4 7.873764 -1.35241100 6
5 0.1371621 2 5.534758 -1.17969925 4
6 0.6226740 4 8.786676 -1.15705659 5
7 -0.3638452 1 6.407712 -0.72113718 5
8 0.9896243 2 9.374095 -0.66681774 9
9 0.1358831 2 2.086996 1.85664439 3
10 -0.7942420 0 8.730721 0.04492028 3
11 -0.2457690 3 2.687042 -1.37655243 2
12 1.4215504 3 7.075115 0.82408260 4
13 1.2500544 3 5.373809 0.53022068 5
14 -2.0085540 5 5.287499 -0.19812226 12
15 -2.5409341 1 6.217131 -0.88139693 5
16 0.5002658 3 2.723290 0.12307794 6
17 0.1059810 0 6.288451 -0.32553662 4
18 -1.2450277 2 2.942365 0.59128965 5
19 0.9986315 4 7.012492 -0.48045326 6
20 0.7709538 1 7.801093 -0.54869693 5
现在假设,您要选择x2大于2的行,并键入以下代码-
> df[df$x2>2]Error in `[.data.frame`(df, df$x2 > 2) : undefined columns selected
它会引发未定义列的错误,因为您在定义目标后忘记了逗号。选择x2大于2的行的适当方法如下所示-
> df[df$x2>2,]x1 x2 x3 x4 x5
1 0.7139625 4 9.321058 0.33297863 4
3 0.5878287 3 7.389898 -0.07847958 5
4 0.9438585 4 7.873764 -1.35241100 6
6 0.6226740 4 8.786676 -1.15705659 5
11 -0.2457690 3 2.687042 -1.37655243 2
12 1.4215504 3 7.075115 0.82408260 4
13 1.2500544 3 5.373809 0.53022068 5
14 -2.0085540 5 5.287499 -0.19812226 12
16 0.5002658 3 2.723290 0.12307794 6
19 0.9986315 4 7.012492 -0.48045326 6
类似地,要选择x2小于2的行,如下所示-
> df[df$x2<2,]x1 x2 x3 x4 x5
7 -0.3638452 1 6.407712 -0.72113718 5
10 -0.7942420 0 8.730721 0.04492028 3
15 -2.5409341 1 6.217131 -0.88139693 5
17 0.1059810 0 6.288451 -0.32553662 4
20 0.7709538 1 7.801093 -0.54869693 5
同样,x2大于1的行的选择如下-
> df[df$x2>1,]x1 x2 x3 x4 x5
1 0.7139625 4 9.321058 0.33297863 4
2 0.9796581 2 4.298837 -1.47926432 11
3 0.5878287 3 7.389898 -0.07847958 5
4 0.9438585 4 7.873764 -1.35241100 6
5 0.1371621 2 5.534758 -1.17969925 4
6 0.6226740 4 8.786676 -1.15705659 5
8 0.9896243 2 9.374095 -0.66681774 9
9 0.1358831 2 2.086996 1.85664439 3
11 -0.2457690 3 2.687042 -1.37655243 2
12 1.4215504 3 7.075115 0.82408260 4
13 1.2500544 3 5.373809 0.53022068 5
14 -2.0085540 5 5.287499 -0.19812226 12
16 0.5002658 3 2.723290 0.12307794 6
18 -1.2450277 2 2.942365 0.59128965 5
19 0.9986315 4 7.012492 -0.48045326 6
以上是 如何处理R中的错误“子集数据帧时选择了未定义的列”? 的全部内容, 来源链接: utcz.com/z/321686.html