Reputation: 27
I'm working on R matrices and i am unable to add names to rows (titles) and columns(region) with this set of problem. My data set is as follows-
terminator_1 <- c(66.1, 317.6, 657.2)
terminator_2 <- c(54.7, 261.9, 616.9)
terminator_3 <- c(45.6, 249.5, 547.1)
region <- c("UK", "US", "Other")
titles <- c("terminator_1", "terminator_2", "terminator_3")
I want to be able to add names to the matrix's rows (titles) and columns (region)
The am trying to get an o/p like the following-
terminator_1 terminator_2 terminator_3
US 66.1 54.7 45.6
UK 317.2 261.9 249.5
Other 657.2 616.9 547.1
Upvotes: 0
Views: 547
Reputation: 32538
sapply(mget(titles), setNames, region)
# terminator_1 terminator_2 terminator_3
#UK 66.1 54.7 45.6
#US 317.6 261.9 249.5
#Other 657.2 616.9 547.1
Upvotes: 2
Reputation: 50668
Do you mean something like this?
mat <- cbind(sapply(ls()[grep("terminator", ls())], get))
rownames(mat) <- region
# terminator_1 terminator_2 terminator_3
#UK 66.1 54.7 45.6
#US 317.6 261.9 249.5
#Other 657.2 616.9 547.1
Explanation: We use get
to column-bind all numeric
vectors that contain the string "terminator"
from the current environment. Then use rownames
to set the row names of the matrix
.
Or much cleaner & more succinct using mget
(thanks to @d.b)
mat <- do.call(cbind, mget(titles))
rownames(mat) <- region
Upvotes: 2