Skip to content

Fill an empty matrix with a function

2 messages · Maximilian Eckert, David Winsemius

#
Dear Sir oder Madam,

 

I am currently writing my master thesis and I am struggling with R:

 

I have created an empty matrix (M) which has months as row.names and stocks
as column.names and now I want to fill this matrix with values from another
matrix (T). The matrix T has also months as row.names and stocks as
column.names however here I have several  values for each month. Now I want
to count the values which have values bigger or equal to zero (plus 1) and
add them to my matrix M:

 

If I do it manually it would look like: 

 

M[,1] <- t(array((colSums(T[1:22,] > 0))+1))  #here in Matrix T I have 22
values for the month January 

M[,2] <- t(array((colSums(T[23:53,] > 0))+1)) #here in Matrix T I have 30
values for the monh February 

 

Is there a way to do this without a loop as I have a very large data set? I
tried to merge it however it did not work:

 

merge.default(as.data.frame(M), as.data.frame(T), by = "row.names",
function(x){colSums(T[,]>0)+1})

 

Thank you very much,

 

Max
#
22 rows
31 rows were indexed.

How are these rows labelled? What does rownames(M) produce?
If you want code, then you need to provide enough (accurate) information to support such an effort. If this data is n a matrix then duplicate rownames are allow, but if it is a dataframe or if coerced to a data.frame than duplicates are not allowed.
David Winsemius
Alameda, CA, USA