Hi,
I have a table and a vector, e.g.,
Table =
A B C
s1 0 1 2
s2 1 2 1
s3 2 0 1
Vector:
vec <- c(0.01, 0.087, 0.34)
I wish to iterate over the table to isolate pairs of rows and then use the vector to fit a 1st order linear regression model (Y~A*B). My problem is that I wish to initiate a matrix outside the main for loop and append the variable 'p_value' to that matrix after each iteration.
The code to isolate the p-values is given below:
for (rows in 1:nrow(Table)) {
li_row <- Table[rows,] # Extract a single row
row <- unlist(li_row) # Convert to vector
for (other in 1:nrow(Table[2, ])) {
li_row_2 <- Table[other,] # Extract a different single row
row_2 <- unlist(li_row_2)
lin_reg <- lm(vec ~ row*row2) # Call 1st order linear model
summ <- summary(lin_reg) # Store results summary
f_stat <- summ$fstatistic # Extract F-statistic data
p_value <- fstat[1] # Extract p-value [**The value to append to matrix**]
}
}
}}
In short, upon each iteration, I wish to add the 'p-value' to a matrix. I know a priori how big the matrix will be and also know what labels to attach to rows and columns.
Thanks,
S ;-)
1 answer
Quick and dirty answer; concatenate all your p-values into a single vector as you progress
vec <- c(vec, p_value)
and at the end, convert to a matrix
matrix(c(0, 1, 2, 1, 2, 1, 2, 0, 1), nrow = 3)
Better answer; don't iteratively append, but rather map a function down the rows of your table and use R's built-in vectorisation to create a matrix.
A toy example below applies an anonymous function to each row y of matrix x, returning a new matrix. The function adds the row y to another row, also from x, but chosen randomly (without replacement).
x <- matrix(c(1, 2, 3, 10, 10, 10, 4, 5, 6), nrow = 3)
apply(x, 2, function(y) y + x[sample(1:nrow(x), 1), TRUE])
Log in to answer this question.
What are you expecting 1:nrow(Table[2, ]) to evaluate to? This is the same as asking for 1:NULL because Table[2, ] is a vector and has nrow of NULL