Is there a way, in R, to save a whole vector into one value of a matrix or data frame, without having to combine it into a single value first?
For example, if I had a vector..
pk<-c(0.021477,0.021114,0.022794,0.014858,0.009690,0.003255,0.002715)
and a matrix..
tst<-matrix(data=NA,nrow=4,ncol=4)
is there anyway of saying, for example..
tst[1,1]<-pk
?
I know I could paste the vector together, but I'm wondering whether there's a way of avoiding this? It's a matter of efficiency as the actual matrix is 33427 x 33427, with each vector ~ 300 values long, and I need to run further analysis on each value in the matrix. I'm hoping to find a way to speed up the analysis.
You can use one of the following two methods to convert a matrix to a data frame in R: #convert matrix to data frame df <- as.data.frame(mat) #specify column names colnames (df) <- c ('first', 'second', 'third', ...)
There will be times that you will want to work with your data organized into a matrix. In R a matrix is an M x N collection of data items. They must all be of the same data type and each row and column must be the same size. You have conveniently created four vectors that you can use to create a matrix.
A vector can contain numbers, character strings, or logical values but not a mixture. All of the data items in a vector must be the same type. The function c ( ) combines the numeric values from 1 to 10 into a vector. You can also obtain the same result using this The annotation 1:10 indicates the series of values from 1 to 10.
A data frame is a tabular data structure, consisting of rows and columns and implemented as a list. The columns of a data frame can consist of different data types but each column must be a single data type [like a vector]. Because a data frame is, in its structure, a list, there are two ways to access the data items in the data frame.
You can certainly put a vector in each element of a matrix. Try something like
tst<-matrix(data=list(),nrow=4,ncol=4)
tst[[1,1]] <- pk #note double square brackets needed for assignment
It doesn't print 'nicely'
tst
[,1] [,2] [,3] [,4]
[1,] Integer,5 NULL NULL NULL
[2,] NULL NULL NULL NULL
[3,] NULL NULL NULL NULL
[4,] NULL NULL NULL NULL
but elements can be extracted in the obvious ways
> tst[1,1]
[[1]]
[1] 0.021477 0.021114 0.022794 0.014858 0.009690 0.003255 0.002715
#note list
> tst[[1,1]]
[1] 0.021477 0.021114 0.022794 0.014858 0.009690 0.003255 0.002715
#original vector
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With