1

我刚开始使用 R 程序,在弄清楚我的程序出了什么问题时遇到了一些麻烦。我将一个文件导入到我的 R 程序中,在尝试询问“玉米”和“棉花”的均值和标准差时,我不断收到错误“找不到对象玉米”和“找不到对象棉花”。以下是我的程序的开头和我导入的 .txt 文件:

rm(list=ls(all=T))

# data
detach(data)
data<-read.table("D:/stalkeyedflies.txt", header=T)
attach(data)

data
names(data)
summary(data)

# mean and standard deviation of corn
mean(corn)
sd(corn)

# mean and standard deviation of cotton
mean(cotton)
sd(cotton)

这是 .txt 文件的样子:

Treatment   eye.span
corn    2.15
corn    2.14
corn    2.13
cotton  2.12
cotton  2.07
cotton  2.01

非常感谢你提前!!

4

2 回答 2

4

您应该按列进行子集化。例如:

mean(subset(dat,Treatment=='corn')$eye)
[1] 2.14
> mean(subset(dat,Treatment=='cotton')$eye)
[1] 2.066667

或者更好的是,您应该使用tapply按治疗组应用平均值:

tapply(dat$eye.span,dat$Treatment,mean)
    corn   cotton 
2.140000 2.066667 

这里的数据是:

dat <- read.table(text='Treatment   eye.span
corn    2.15
corn    2.14
corn    2.13
cotton  2.12
cotton  2.07
cotton  2.01',header=TRUE)
于 2013-10-30T03:02:50.113 回答
0

data<-read.table("stalkeyedflies.txt", header=T)
data
corn<-data[data$Treatment=="corn",]
# get the subset of corn
mean(corn[,"eye.span"])
# calculate the mean of corn

cotton<-data[data$Treatment=="cotton",]
# get the subset of cotton
sd(cotton[,"eye.span"])
# calculate the sd of cotton

于 2015-05-18T12:44:01.497 回答