简体   繁体   中英

Multiple Matrix Operations in R with loop based on matrix name

I'm a novice R user, who's learning to use this coding language to deal with data problems in research. I am trying to understand how knowledge evolves within an industry by looking at patenting in subclasses. So far I managed to get the following:

# kn.matrices<-with(patents, table(Class,year,firm))
# kn.ind <- with(patents, table(Class, year))

patents is my datafile, with Subclass, app.yr, and short.name as three of the 14 columns

# for (k in 1:37)  
# kn.firms = assign(paste("firm", k ,sep=''),kn.matrices[,,k]) 

There are 37 different firms (in the real dataset, here only 5)

This has given 37 firm-specific and 1 industry-specific 2635 by 29 matrices (in the real dataset). All firm-specific matrices are called firmk with k going from 1 until 37.

I would like to perform many operations in each of the firm-specific matrices (eg compare the numbers in app.yr 't' with the average of the 3 previous years across all rows) so I am looking for a way that allows me to loop the operations for every matrix named firm1,firm2,firm3...,firm37 and that generates new matrices with consistent naming, eg firm1.3yearcomparison

Hopefully I framed this question in an appropriate way. Any help would be greatly appreciated.

Following comments I'm trying to add a minimal reproducible example

year<-c(1990,1991,1989,1992,1993,1991,1990,1990,1989,1993,1991,1992,1991,1991,1991,1990,1989,1991,1992,1992,1991,1993)

firm<-(c("a","a","a","b","b","c","d","d","e","a","b","c","c","e","a","b","b","e","e","e","d","e"))

class<-c(1900,2000,3000,7710,18000,19000,36000,115000,212000,215000,253600,383000,471000,594000)

These three vectors thus represent columns in a spreadsheet that forms the "patents" matrix mentioned before.

it looks like you already have a 3 dimensional array with all your data. You can basically view this as your 38 matrices all piled one on top of the other. You don't want to split this into 38 matrices and use loops. Instead, you can use R's apply function and extraction functions. Just view the help topic on the apply() family and it should show you how to do what you want. Here are a few basic examples

examples:

# returns the sums of all columns for all matrices
apply(kn.matrices, 3, colSums)

# extract the 5th row of all matrices
kn.matrices[5, , ]

# extract the 5th column of all matrices
kn.matrices[, 5, ]

# extract the 5th matrix
kn.matrices[, , 5]

# mean of 5th column for all matrices
colMeans(kn.matrices[, 5, ])

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