Home > Software engineering >  keep the name of the input vector's element in the output of the function in R
keep the name of the input vector's element in the output of the function in R

Time:10-18

I have two functions f1 and f2. In its output, f1 always keeps the name of the element of the inputted vector x.

But in its output, f2 always deletes the name of the element of the inputted vector x.

Is there a way for f2 to keep the name of the element in its output just like f1?

x <- 1:10
x <- setNames(x, letters[1:10])

f1 <- function(x, n){
  
  sort(x)[n]
} 
# EXAMPLE OF USE:
f1(x, 2)

# OUTPUT:
# b       # Notice "b"
# 2

f2 <- function(x, n){
  
  len <- length(x)
  sort(x, partial = len-n 1)[len-n 1]
}

# EXAMPLE OF USE:
f2(x, 2)

# OUTPUT:
# [1] 9     # Notice no name is attached to 9.

CodePudding user response:

In sort function, it says that if partial is not null, names are discarded. See sort function documentation. In f2, sort(x, partial = len-n 1)[len-n 1], just little more messy,

f2 <- function(x, n){
  
  len <- length(x)
  x[x == sort(x, partial = len-n 1)[len-n 1]]
}
f2(x, 2)

i 
9

but this will keep name of value.

  • Related