Reputation: 99
I want to extract some values from a factor, but instead of having one index string i have a data.matrix containing multiple columns, all containing indexes.
I have:
f<-factor(c('a','b','c','a'))
d<-data.matrix(data.frame(t=c(1,3,2),u=c(2,3,4)))
> f[d]
[1] a c b b c a
But instead of having all return values in one vector, I would like to maintain the data.matrix structure like this:
[,1][,2]
a b
c c
b a
How is this possible i en elegant way?
Upvotes: 2
Views: 117
Reputation: 193517
I'm not sure of the definition of elegant, but you are essentially looking for dim()
.
You can do this in a cryptic way with dim<-()
, like this:
`dim<-`(f[d], dim(d))
## [,1] [,2]
## [1,] a b
## [2,] c c
## [3,] b a
## Levels: a b c
Less cryptic would be the following (though note the slight difference in the result).
matrix(f[d], ncol = ncol(d))
## [,1] [,2]
## [1,] "a" "b"
## [2,] "c" "c"
## [3,] "b" "a"
If you're after a data.frame
, then try:
as.data.frame.matrix(`dim<-`(f[d], dim(d)))
## V1 V2
## 1 a b
## 2 c c
## 3 b a
Or data.frame(matrix(f[d], ncol = ncol(d)))
.
Upvotes: 4