2

我想对被捕时男女的平均年龄进行 t 检验。但是,我的数据排列如下:

Sex: Age:
M    21
F    31
F    42
M    43

有没有办法将性别类别分为两个单独的类别(男性和女性)以执行我的 t 检验?或者在一个类别中执行 t 检验?已经提出了类似的问题,但似乎没有一个对我的数据集有效。感谢您提供的任何指导!

4

3 回答 3

4

首先,很好的第一个问题,很高兴看到高中生学习统计编程!

第二:您自己正在寻找答案,这应该可以帮助您到达那里。

我在做一些假设:

  1. 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 检验,您必须按名称询问数据框和带有年龄的列,例如: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 检验是一个简单的比较:

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 

看来您的问题出在代码中的三个位置:

  1. gender=="F"在列命名时使用Sex:
  2. 不使用逗号[,]来指定行然后列
  3. 如果它确实仍然是两列,则不解决 t.test 中的 $Age 列

上面的代码应该可以让你到达你需要的地方。

于 2017-05-19T04:10:15.983 回答
0

比较男性年龄和女性年龄的 t 检验可以如下进行:

df = data.frame(
    gender = c("M", "F", "F", "M"),
    age = c(21, 31, 42, 43)
)

t.test(age ~ gender, data = df)

这是根据您的问题似乎最相关的测试。

当您说“在一个类别中执行 t 检验”时,我不确定您的意思:您可以将一组值与某个已知参考值(如 0)进行比较,但我不确定这能说明什么你(除了你样本中的男性不是 0 岁)。

于 2017-05-19T03:51:19.890 回答
0

你可以试试这段代码:

t.test(Age ~ Sex, paired = FALSE, data = datasetName)

它应该为您提供相同的结果,而无需创建更多子集。

于 2017-06-26T15:13:40.277 回答