[R] Find the max entry in column 2 - that satisfies a condition given a fixed entry in column 1

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Fri Jun 21 07:47:15 CEST 2019



Às 10:15 de 20/06/19, Vangelis Litos escreveu:
> 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);

This code works but there are several issues with it.

1) c(1) is exactly the same as just 1. Try running

identical(c(1), 1)

2) You end the line with a semi-colon. This is not needed.
In fact,

the semi-colon is the INSTRUCTIONS SEPARATOR

so what you end up with is 2 instructions, one on the left of the ; and 
the other, the NULL instruction, on the right. What the parser sees and 
processes is


3) Then in the next line you transpose the matrix you have created. Much 

y <- rbind(1, 2)
identical(x, y)    # TRUE

>> plain = expand.grid (sort (unique (c (0, x))), sort (unique (c (0, x))));

4) Now you combine the matrix you have created with a new element, 0.

c(0, x)

The output of this is no longer a matrix, it's a vector without the dim 

identical(c(0, x), c(0, 1, 2))    # TRUE

> 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

The following function does this.

fun <- function(X, val){
   u <- sort(unique(X))
   plain <- expand.grid(u, u)
   w <- which(plain[, 1] == val)
   w[which.max(plain[w, 2])]

fun(c(0, x), 0)
#[1] 7
fun(c(x, 0, x), 0)
#[1] 7

> Then I want to create a column vector b (9x1) that has zero everywhere apart from row 7.

And what would be the non-zero value? The max in column 2?

b <- numeric(nrow(plain))    # creates a vector of 9 zeros
i <- fun(c(0, x), 0)
b[i] <- new_value

# or maybe

b[i] <- plain[i, 2]

The first and the last instructions have an obvious problem, 'plain' 
only exists inside the function fun(), it will have to be created elsewhere.

Hope this helps,

Rui Barradas
> 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.

More information about the R-help mailing list