Error in apply(df$var1, 2, mean) : dim(X) must have a positive length
目录
Error in apply(df$var1, 2, mean) : dim(X) must have a positive length
问题:
#出现错误是因为apply()函数必须应用于dataframe或matrix,我们尝试将其应用于数据帧中的特定列则发生错误。
#create data frame
df <- data.frame(points=c(99, 97, 104, 79, 84, 88, 91, 99),
rebounds=c(34, 40, 41, 38, 29, 30, 22, 25),
blocks=c(12, 8, 8, 7, 8, 11, 6, 7))
#view data frame
df
#attempt to calculate mean of 'points' column
apply(df$points, 2, mean)
解决:
#计算所有列的均值
#calculate mean of every column in data frame
apply(df, 2, mean)
points rebounds blocks
92.625 32.375 8.375
#计算部分列的均值
#calculate mean of 'points' and 'blocks' column in data frame
apply(df[c('points', 'blocks')], 2, mean)
points blocks
92.625 8.375
#计算其中一列的均值
#calculate mean of 'points' column
mean(df$points)
[1] 92.625
完整错误:
> #create data frame
> df <- data.frame(points=c(99, 97, 104, 79, 84, 88, 91, 99),
+ rebounds=c(34, 40, 41, 38, 29, 30, 22, 25),
+ blocks=c(12, 8, 8, 7, 8, 11, 6, 7))
>
> #view data frame
> df
points rebounds blocks
1 99 34 12
2 97 40 8
3 104 41 8
4 79 38 7
5 84 29 8
6 88 30 11
7 91 22 6
8 99 25 7
>
>
> #attempt to calculate mean of 'points' column
> apply(df$points, 2, mean)
Error in apply(df$points, 2, mean) : dim(X)的值必需是正数
>