I would like to create a matrix of indicator variables. My initial thought was to use model.matrix, which was also proposed here: Automatically expand the R-factor into a set of 1/0 indicator indicators for each level factor
However, model.matrix does not seem to work if the coefficient has only one level.
Here is an example of a data set with three levels in the βareaβ of a factor:
dat = read.table(text = " reg1 reg2 reg3 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 1 ", sep = "", header = TRUE) # model.matrix works if there are multiple regions: region <- c(1,1,1,1,1,1,2,2,2,3,3,3,3) df.region <- as.data.frame(region) df.region$region <- as.factor(df.region$region) my.matrix <- as.data.frame(model.matrix(~ -1 + df.region$region, df.region)) my.matrix # The following for-loop works even if there is only one level to the factor # (one region): # region <- c(1,1,1,1,1,1,1,1,1,1,1,1,1) my.matrix <- matrix(0, nrow=length(region), ncol=length(unique(region))) for(i in 1:length(region)) {my.matrix[i,region[i]]=1} my.matrix
Effective for a loop and seems simple enough. However, I struggled to come up with a solution that is not related to cycles. I can use the cycle above, but I try to wean myself from them. Is there a better way?
matrix r
Mark Miller Dec 22 2018-12-12T00: 00Z
source share