How to extract the p-value from t test in R?

R ProgrammingServer Side ProgrammingProgramming

To extract the p-value from t test in R, we can follow the below steps −

  • First of all, create a data frame with numerical column or a numerical vector.
  • Then, use t.test function to perform the test and put $p.value at the end to extract the p-value from the test output.

Example1

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-rnorm(20,5,1)
df<-data.frame(x)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x
1 5.854093
2 6.075394
3 5.114147
4 3.672250
5 6.519127
6 5.145577
7 3.005657
8 2.994189
9 6.031218
10 4.981937
11 5.359909
12 4.914696
13 4.767514
14 6.090447
15 5.644259
16 6.210392
17 4.097178
18 5.242026
19 4.999231
20 5.494340

Perform the t test and extract the p-value

Using t.test function to perform the t-test on column x of df and extract the p-value with $p.value −

 Live Demo

x<-rnorm(20,5,1)
df<-data.frame(x)
t.test(df$x,mu=5.8,alternative="less")$p.value

Output

[1] 0.003168284

Example2

Create the vector

Let’s create a vector as shown below −

 Live Demo

y<-sample(1:1000,200)
y
[1] 761 40 629 167 687 200 873 481 218 708 315 649 119 16 603 177 733 852
[19] 925 940 693 620 146 416 13 790 79 464 801 543 91 754 505 235 549 770
[37] 630 991 762 703 805 713 968 316 883 52 717 747 121 756 773 308 283 372
[55] 425 918 391 997 276 912 253 874 281 76 759 658 197 516 917 126 26 615
[73] 240 10 84 676 766 553 286 307 877 778 560 994 736 75 295 697 864 256
[91] 70 50 739 686 66 902 836 125 606 194 819 462 900 891 213 68 808 834
[109] 501 945 325 140 107 531 311 755 169 361 663 577 590 589 211 889 684 257
[127] 580 180 318 872 839 413 936 503 246 190 333 178 46 434 894 365 669 937
[145] 884 752 840 656 698 757 984 772 933 139 317 626 591 502 189 53 410 751
[163] 351 72 645 944 170 465 628 639 243 844 493 855 709 913 710 993 858 504
[181] 596 585 350 618 942 934 980 490 782 699 722 284 740 715 562 156 210 767
[199] 621 19

Perform the t test and extract the p-value

Using t.test function to perform the t-test on vector x and extract the p-value with $p.value −

 Live Demo

y<-sample(1:1000,200)
t.test(y,mu=500,alternative="greater")$p.value

Output

[1] 0.04181906
raja
Published on 04-Aug-2021 11:25:42
Advertisements