arrays - R: Keeping numbers of loops flexible (by addressing dimensions without indexing) -
hello little , big helpers,
i have problem in r concerning dataset variable number of dimensons, causing changing number of for-loops. provide example similar problem (albeit of course different topic).
imagine have following data set: in our r-wonderland there 5 states. in each state there 6 towns. in each town there 10 burger restaurants. know burger price each of 10*6*5 = 300 restaurants. i'd know cheapest burger every town in every state.
x <- rnorm(300,5,1) # create random "burger prices" mean=5$ , std.dv 1$ 300 restaurants x_array <- array(x,dim=c(10,6,5)) # prices in order: 1st dim = 10 restaurants per town, 2nd dim = 6 towns in state, 3rd dim = 5 states x_subset <- array(0,dim=c(dim(x_array)[2],dim(x_array)[3])) # prepare subset contain "location" of cheapest burger in town & state # find cheapest burger each town in each state -> want keep flexible in terms of number of dimensions/loops (i in 1:dim(x_array)[2]){ (j in 1:dim(x_array)[3]){ x_subset[i,j] <- which(x_array == min(x_array[,i,j])) } } by eliminating variation of restaurants reduce original data set 1 dimension (10 restaurants -> cheapest 1 restaurant).
the problem in case dimesions not fixed. imagine i'd add different nations data set, there might 10 restaurants in 6 towns , 5 states of 4 nations on 3 continents - 5d problem result in x_subset containing 4 dimensions. i'd have set loop of depth four.
how keep numbers of loops flexible? had similar problem able solve using
expand.grid() but not reduce dimension one. there new item restaurant 1,2,3,... each town, state (,nation, continent, ...). need cheapest restaurant (> min()) on first dim , combinations rest of dataset.
i think possible if solve synthax issue:
x_subset_vector <- x_subset[,1] # how write without knowing n° of dimensions of x_subset? like: "get values of first item (in case: "column") in second dimension" or burger example:
x_subset_vector <- x_subset[,1,1] # 3d problem ([restaurants, towns, states]) x_subset_vector <- x_subset[,1,1,1,1] # 5d problem ([..., nation,continent]) in easy words: how automize numbers of "commas" in index of x_subset?
sorry making hungry. deserve hell of great burger helping me one!
thank much, guys!
Comments
Post a Comment