4

これは私を永遠に悩ませてきました。次の点を考慮してください。

# Part A #
# Make a silly simple matrix with column names
x = matrix(1:4, ncol = 2)
colnames(x) = c("a","b")

# Part B #
# Pick out the first row of the matrix.  This is not a matrix, 
#   and the column names are no longer accessible by colnames()
y = x[1,]
y
is.matrix(y)
colnames(y)

# Part C #
# But here is what I want:
y = matrix(x[1,], nrow = 1, dimnames = list(c(), colnames(x)))

より少ない処理ステップまたはより少ないコードでパート C を達成する方法はありますか? 同じことをするのとほぼ同じくらい短いコマンドがあるはずx[1,]です。

4

2 に答える 2

5

次のように設定するだけdrop=FALSEです:

> y = x[1,, drop=FALSE]
> y
     a b
[1,] 1 3
于 2013-09-25T17:53:31.823 に答える
4

どうですか

x[1,,drop=FALSE]
     a b
[1,] 1 3
于 2013-09-25T17:53:48.950 に答える