简体   繁体   中英

Assigning values to a matrix in R

I could not find a solution to this in stack exchange.

I have the following example matrix (showing only the first 8 values) that show the sum of 20 fair coin flips (heads=1, tails=0).

print(Flips)
     [,1]
 [1,] 16  
 [2,] 11  
 [3,]  8   
 [4,]  9   
 [5,]  9   
 [6,]  7   
 [7,] 10  
 [8,] 14  

I have p-values for all possible successful flips (heads), 0 through 20 saved in a separate object, pvalues (calculated using binomial distribution)

read.table("p_values.txt", header=T)
   ID Heads    p_value
1   1     0 0.0000010
2   2     1 0.0000191
3   3     2 0.0001812
4   4     3 0.0010872
5   5     4 0.0046206
6   6     5 0.0147858
7   7     6 0.0369644
8   8     7 0.0739288
9   9     8 0.1201344
10 10     9 0.1601791
11 11    10 0.1761971
12 12    11 0.1601791
13 13    12 0.1201344
14 14    13 0.0739288
15 15    14 0.0369644
16 16    15 0.0147858
17 17    16 0.0046206
18 18    17 0.0010872
19 19    18 0.0001812
20 20    19 0.0000191
21 21    20 0.0000010

What I would like to do is assign a new column to the matrix "Flips" which assigns a p-value to each row based on the data that I have in my p-values file.

So for example, the new matrix would have ap value of 0.00462055 assigned to row [,1]. I'm pretty new to R programming, and I know how to assign a new column using cbind, but I'm not sure how I can get R to assign a p-value to its corresponding number of successes/20...

如果数据未排序,则可以使用match

 cbind(Flips, df1[,3][match(Flips[,1], df1$Heads)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM