变量的无效类型(列表) [英] invalid type (list) for variable
问题描述
我正在尝试在 R 中运行 anova 模型.我有一个包含 3 行 12 列的数据文件.每行是解释变量特定级别的数据.单元格 [i,j] 是水平 i 的第 j 个响应.该文件是.dat"扩展名.我正在运行以下 R 代码以尝试获取 36 x 2 数据帧来运行 anova 模型而不是 3 x 12 原始数据帧:
I am trying to run an anova model in R. I have a data file which contains 3 rows and 12 columns. Each row is data for a particular level of the explanatory variable. Cell [i,j] is the j'th response for level i. The file is ".dat" extension. I am running the following R code to try to get a 36 by 2 data frame to run the anova model instead of the 3 by 12 original data frame:
data <- read.table("usedcar.dat", row.names = 1)
young <- data[1,]
med <- data[2,]
old <- data[3,]
Price <- c(young, med, old)
Age <- as.factor(c(rep(1,12), rep(2,12), rep(3,12)))
data <- cbind(Age, Price)
data <- as.data.frame(data)
但是当我尝试从中获取 anova 模型时,我收到了无效列表类型错误:
But when I try to get the anova model out of it I get the invalid list type error:
m1 <- aov(Price ~ Age, data = data)
Error in model.frame.default(formula = Price ~ Age, data = data, drop.unused.levels = TRUE) : invalid type (list) for variable 'Price'
我在这里做错了什么?
这是一个随机矩阵,如果有帮助的话:
Here's a random matrix if that will help:
replicate(12, rnorm(3))
这里是 str(data) 结果:
Here is the str(data) result:
str(data)
'data.frame': 36 obs. of 2 variables:
$ Age :List of 36
..$ 1 : int 1
..$ 2 : int 1
..$ 3 : int 1
...
..$ 36: int 3
$ Price:List of 36
..$ 1 : int 2300
...
..$ 36: int 2075
推荐答案
tl;dr 数据框的行是列表,而不是数字向量.当您 read.table()
时,您会得到一个数据框(因此,像我之前所做的那样,构建矩阵不会复制问题).
tl;dr rows of data frames are lists, not numeric vectors. When you read.table()
you get a data frame (so constructing a matrix, as I did before, doesn't replicate the problem).
data <- as.data.frame(matrix(rnorm(36),nrow=3))
young <- data[1,]; med <- data[2,]; old <- data[3,]
Price <- c(young, med, old)
str(Price)
## ## List of 36
## ## $ V1 : num 0.648
## ## $ V2 : num 0.157
## ## ...
事实上这是一个列表,而不是一个数字向量,这是一个问题.有多种处理方法.最简单的是unlist()
:
The fact that this is a list, not a numeric vector, is a problem.
There are a variety of ways of handling this. The easiest is unlist()
:
dd <- data.frame(Age,Price=unlist(Price))
aov(Price~Age,dd)
这篇关于变量的无效类型(列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!