Reputation: 31
I am trying to get the max within a row, for a particular subset of rows.
a <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5), x = rnorm(5), y = rnorm(5), z = rnorm(5))
a
a b c x y z
1 -0.99415010 0.06177776 1.1224987 -0.60239594 -0.53526479 1.26826763
2 -1.17727409 -0.60488488 1.6509299 0.65014481 -0.91940395 0.47520214
3 -0.04944379 1.47238123 -1.1691980 0.07603221 -0.05844166 -0.24809870
4 -0.05230395 -2.52972650 -0.1170329 0.57833492 0.61692175 -0.16939056
5 -0.61666540 0.02606907 0.2438158 -1.01048883 -1.23118019 0.09784697
> names(a)[apply(a, 1, which.max)]
[1] "z" "c" "b" "y" "c"
Is there a way to subset the data so that I only get which.max results for columns x, y, and z? When I try to subset the columns I need, I get this error:
Error in names(---)[apply(----[, 13:68], 1, which.max)] :
invalid subscript type 'list'
Thank you!
Upvotes: 0
Views: 573
Reputation: 886948
You could also try:
b1 <- a[,letters[24:26]]
names(b1)[max.col(b1)]
#[1] "x" "z" "y" "y" "y"
set.seed(42)
a <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5), x = rnorm(5), y = rnorm(5), z = rnorm(5))
Upvotes: 0
Reputation: 1437
How about
b <- a[,c("x","y","z")]
names(b)[apply(b, 1, which.max)]
or
names(a[,4:6])[apply(a[,4:6], 1, which.max)]
Upvotes: 1
Reputation: 24535
Following may help (my 'a' values are different from yours since you did not use set.seed):
xx = apply(a, 1, which.max)
names(a)[xx[xx>3]]
[1] "y"
If you want to analyze only x,y,z columns:
> a = a[,4:6]
> names(a)[apply(a, 1, which.max)]
[1] "x" "y" "x" "z" "y"
Upvotes: 1