[R] Find the max entry in column 2 - that satisfies a condition given a fixed entry in column 1
Richard O'Keefe
r@oknz @end|ng |rom gm@||@com
Sat Jun 22 08:23:24 CEST 2019
I have read your message four times in the last couple of days,
but I still have very little idea what you want.
Let's try some things I've gleaned.
You have a matrix with 9 rows and 2 columns, and there is a 2
somewhere in column 1.
> m <- matrix(1:18, nrow=9, ncol=2)
> m[c(4,7,8),1] <- 2
> m
[,1] [,2]
[1,] 1 10
[2,] 2 11
[3,] 3 12
[4,] 2 13
[5,] 5 14
[6,] 6 15
[7,] 2 16
[8,] 2 17
[9,] 9 18
You want to select rows where column 1 is 2.
> m[,1] == 2
[1] FALSE TRUE FALSE TRUE FALSE FALSE TRUE TRUE FALSE
You want to select the corresponding elements from column 2.
> m[m[,1] == 2, 2]
[1] 11 13 16 17
You want the maximum of these elements.
> max(m[m[,1] == 2, 2])
[1] 17
You can do pretty amazing things with indexing in R without any extra
packages.
Of course, I have almost certainly misunderstood you.
Perhaps you can ask again, maybe with an example?
On Fri, 21 Jun 2019 at 11:50, Vangelis Litos <Redondo5_447 using hotmail.com>
wrote:
> I am using R and I created based on a vector x, a grid (named: plain) -
> where zero is included. This gives me a 9x2 ``matrix''.
>
> > x_t = cbind(c(1),c(2));
> > x = t(x_t);
>
> > plain = expand.grid (sort (unique (c (0, x))), sort (unique (c (0, x))));
>
> My aim is to focus on column 1 and take i.e the first entry (then the
> second, the third entry etc through a loop) of the unique (c (0, x)) vector
> (==0) [rows 1, 4 and 7] and find the maximum value (entry) in the second
> column of the matrix that satisfies a condition.
>
> Let say that the condition is satisfied when at column 2 the value is 2.
> That is I want row 7 to be selected
>
> Then I want to create a column vector b (9x1) that has zero everywhere
> apart from row 7.
>
> Can anybody help me with this?
>
> Thank you in advance.
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list