ChatGPT解决这个技术问题 Extra ChatGPT

How to subset matrix to one column, maintain matrix data type, maintain row/column names?

When I subset a matrix to a single column, the result is of class numeric, not matrix (i.e. myMatrix[ , 5 ] to subset to the fifth column). Is there a compact way to subset to a single column, maintain the matrix format, and maintain the row/column names without doing something complicated like:

matrix( myMatrix[ , 5 ] , dimnames = list( rownames( myMatrix ) , colnames( myMatrix )[ 5 ] )

J
Joshua Ulrich

Use the drop=FALSE argument to [.

m <- matrix(1:10,5,2)
rownames(m) <- 1:5
colnames(m) <- 1:2
m[,1]             # vector
m[,1,drop=FALSE]  # matrix

I would have sworn I saw this just recently but it may have been the analogous dataframe behavior that was being questioned: stackoverflow.com/questions/6941985/…
If you want to index by only the first dimension, can you use drop as follows: m[1,,drop=FALSE]
To give an example on statistical grounds, using Cooks' D distances, and then selecting values based on a cut off value e.g. 0.1, it will result the cooksD values with their respective number of row in the relative dataset cooksd<-as.data.frame(cooks.distance(ft1)) cooksD_outliers<-cooksd[cooksd>0.1,drop=FALSE,]
result<-apply(temp,1,function(x) tapply(x, genesymbol,function(x) mean(x,na.rm=T))) How to deal with the problem that result is a array, but actually, I want it to be a one column data frame ? Thanks
@ShichengGuo: You should ask a new question.