Shaxi Liver
Shaxi Liver

Reputation: 1120

Filling matrix with data from two columns of dataframe

I am so desperated and even I am ready to lose some more rep points but I have to ask it. (Yes, I read some threads about it).

I created a dataframe with only 2 columns I want to put to the matrix (I didn't know how to pick just 2 columns from whole data):

    tbl_corel <- tbl_end[,c("diff", "abund_mean")]

In next step I created and empty matrix:

## Creating a empty matrix to check the correlation between diff and abund_mean
mat_corel <- matrix(0, ncol = 2)
colnames(mat_corel) <- c("diff", "abund_mean")

I tried to use that function to fill the matrix with the data:

mat_corel <- matrix(tbl_corel), nrow = 676,ncol = 2)

Of course I had to check manually how many rows I have in my data frame... It doesn't work. Tried that function as well:

mat_corel[ as.matrix(tbl_corel) ] <- 1

It doesn't work. I'd be so grateful for the help.

  diff abund_mean
1    0 3444804.80
2    0  847887.02
3    0   93654.19
4    0  721692.76
5    0  382711.04
6    1  428656.66

Upvotes: 0

Views: 2991

Answers (1)

juba
juba

Reputation: 49033

If you want to create a matrix from your two-columns data frame, there is a more direct and simpler way : just transform you data frame as a matrix directly :

mat_corel <- as.matrix(tbl_corel)

But if you just want to compute a correlation coefficient, you can do it directly from your data frame :

cor(tbl_end$diff, tbl_end$abund_mean)

Upvotes: 6

Related Questions