当我将矩阵子集化为单个列时,结果是类数字,而不是矩阵(即myMatrix [,5]到第五列的子集).是否有一种紧凑的方法可以将单个列子集化,维护矩阵格式,并维护行/列名称,而无需执行以下操作:
matrix( myMatrix[ , 5 ] , dimnames = list( rownames( myMatrix ) , colnames( myMatrix )[ 5 ] )
Run Code Online (Sandbox Code Playgroud) 似乎在访问具有1列的表时,访问的操作会抛弃列信息.如果有超过1列,则保留此信息.
例如
表中有1个项目:
> example1 <- data.frame( items = c("A","B","B","C","C","C","C")
+ , time = ISOdate(2222,1,1) )
> table1 <- table(example1)
> table1
time
items 2222-01-01 12:00:00
A 1
B 2
C 4
> barplot(table1, legend=T)
> table1.ordered <- table1[c(3,2,1),] # reorder
> table1.ordered
C B A
4 2 1
> barplot(table1.ordered, legend=T) # time column thrown away
Run Code Online (Sandbox Code Playgroud)
现在表中有2个项目 :( 在此示例中添加到example1)
> example2 <- rbind(example1 , data.frame(items = NA, time = ISOdate(3333,1,1)) )
> example2
items time
1 …Run Code Online (Sandbox Code Playgroud) R几乎每天都一次又一次地让我感到惊讶:
m <- matrix( 1:6, ncol=2 )
while( dim(m)[1] > 0 ){
print(m);
m <- m[-1,]
}
Run Code Online (Sandbox Code Playgroud)
得到:
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
[,1] [,2]
[1,] 2 5
[2,] 3 6
Error in while (dim(m)[1] > 0) { : argument is of length zero
Run Code Online (Sandbox Code Playgroud)
R有1xn矩阵的问题或我的错误在哪里?
> nrow( m[-c(2,3), ] )
NULL
> dim( m[-c(2,3), ] )
NULL
> m[-c(2,3), ][,1]
Error in m[-c(2, 3), ][, 1] : incorrect number of dimensions
> str( m[-c(2,3), …Run Code Online (Sandbox Code Playgroud)