Home > Enterprise >  Function for absolute value of list elements in R
Function for absolute value of list elements in R

Time:12-02

I am trying to create an R function that converts any negative values in a list of values to be positive:

x <- c(5,-8,11)


abs_function <- function(A){
  n <- nrow(A)
  for (i in n) {
    if (A[i,]<0) {-A}
    else if (A[i,]>0) {A}
  }
  return(A)
}

But when I try:

abs_tfn(x)

it returns:

[1]  5 -8 11

hence value -8 does not convert to 8.

Am I missing something basic here?

Thanks in advance for your help.

CodePudding user response:

There's a default function for this for a vector: abs(), so you can do abs(x).

For a list x <- list(5, -8, 11), something like the following works:

fun <- function(list) {
  for (i in 1:length(list)) {
    list[[i]] <- abs(list[[i]])
  }
  return(list)
}

fun(x)
  • Related