Home > Blockchain >  R: How would I remove the values in the bottom right half of a square so that the result is a triang
R: How would I remove the values in the bottom right half of a square so that the result is a triang

Time:07-26

If I have DF1 as such:

a <- c(5,10,15)
b <- c(5,10,15)
c <- c(5,10,15)
DF1 <- data.frame(a,b,c)
DF1

   a  b  c
1  5  5  5
2 10 10 10
3 15 15 15

How would I remove the bottom right half of the square such that the result looks like:

   a  b  c
1  5  5  5
2 10 10 NA
3 15 NA NA

CodePudding user response:

Reversing column indices of lower.tri:

DF1[lower.tri(DF1)[,ncol(DF1):1]] <- NA
DF1
#>    a  b  c
#> 1  5  5  5
#> 2 10 10 NA
#> 3 15 NA NA

CodePudding user response:

It is a bit hacky, but in essence you want to use the function lower.tri and mirror the resulting matrix. I've wrote a function lower.tri.right which does exactly that.

a <- c(5,10,15)
b <- c(5,10,15)
c <- c(5,10,15)
x <- data.frame(a,b,c)
lower.tri.right <- function(x, repl = NA, diag = FALSE){
  tmp <- lower.tri(x)
  tmp <- tmp[,ncol(tmp):1]
  x[tmp] <- repl
  return(x)
}
lower.tri.right(x)

   c  b  a
1  5  5  5
2 10 10 NA
3 15 NA NA

With this solution, you can choose to convert the diagonal aswell and you can choose what to use as the replacement (repl).

CodePudding user response:

I`m sure there is a more clean and elegant way but this will do the job

a <- c(5,10,15)
b <- c(5,10,15)
c <- c(5,10,15)

DF1 <- data.frame(a,b,c)

  a  b  c
1  5  5  5
2 10 10 10
3 15 15 15

len <- ncol(DF1)

for (i in 2:nrow(DF1)){
 DF1[i,][len:ncol(DF1)] <- NA
 len <- len - 1
}

> DF1
   a  b  c
1  5  5  5
2 10 10 NA
3 15 NA NA

CodePudding user response:

You can do it explicitly by asking for the exact element positions to be set to NA:

DF1[2, 3] = DF1[3, 2] = DF1[3, 3] = NA

Output:

   a  b  c
1  5  5  5
2 10 10 NA
3 15 NA NA

Or, if the directionality of your matrix object (DF1) is open to change, you can better do this using the lower.tri function as follows:

DF1[lower.tri(DF1)] <- NA

Output:

   a  b  c
1  5  5  5
2 NA 10 10
3 NA NA 15
  •  Tags:  
  • r
  • Related