首先,很好的第一个问题,很高兴看到高中生学习统计编程!
第二:你自己正在寻找答案的路上,这应该可以帮助你到达那里。
我在做一些假设:
-
prof 是您的数据框的名称
2 您希望在 t 检验中比较 prof 的性别年龄
你的逻辑是正确的。我在prof 数据框中添加了一些额外的观察结果,但它应该是这样工作的:
# this is a comment in the code, not code, but it explains the reasoning, it always starts with hash tag
women<-prof[which(prof$Sex=="F"),] #notice the comma after parenthesis
men<-prof[which(prof$Sex=="M"),] #notice the comma after parenthesis here too
逗号左侧选择具有该数据 == “某物”的行。逗号右边告诉你哪些列,留空告诉 r 包括所有列。
head(men);head(women) # shows you first 6 rows of each new frame
# you can see below that the data is still in a data frame
Sex Age
1 M 21
4 M 43
5 M 12
6 M 36
7 M 21
10 M 23
Sex Age
2 F 31
3 F 42
8 F 52
9 F 21
11 F 36
所以要对年龄进行 t-test,您必须按名称和带有年龄的列询问数据框,例如:men$Age
t.test(women$Age, men$Age) #this is the test
# results below
Welch Two Sample t-test
data: women$Age and men$Age
t = 0.59863, df = 10.172, p-value = 0.5625
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-11.93964 20.73964
sample estimates:
mean of x mean of y
36.4 32.0
在 R 中几乎总是有不止一种方法。有时初始排序更复杂,但处理数据更容易。因此,如果您不想从数据框中解决年龄问题,您可以要求初始子集中的列
women<-prof[which(prof$Sex=="F"),"Age"] #set women equal to just the ages where Sex is 'F'
men<-prof[which(prof$Sex=="M"), "Age"]#set men equal to just the ages where Sex is 'M'
再次查看您的数据,这次只是每个变量的年龄向量:
head(women); head(men)
[1] 31 42 52 21 36
[1] 21 43 12 36 21 23
那么你的 t-test 就是一个简单的比较:
t.test(women,men)
# notice same results
Welch Two Sample t-test
data: women and men
t = 0.59863, df = 10.172, p-value = 0.5625
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-11.93964 20.73964
sample estimates:
mean of x mean of y
36.4 32.0
看来您的问题出在代码中的三个位置:
- 当列名为
Sex: 时使用gender=="F"
- 在
[,] 中不使用逗号来指定行和列
- 不处理 t.test 中的 $Age 列(如果它确实仍然存在)
两列
上面的代码应该可以让你到达你需要的地方。