Using backticks and operators in applying family functions

In a recent answer, I saw an applicable family function with inline assignments and cannot generalize it.

lst <- list(a=1, b=2:3)
lst
$a
[1] 1

$b
[1] 2 3

      

This cannot yet be done in data.frame due to unequal lengths. But by calling the maximum length of the list, it works:

data.frame(lapply(lst, `length<-`, max(lengths(lst))))
   a b
1  1 2
2 NA 3

      

It works. But I never used arrow assignment in the functions I applied. I tried to figure it out by summarizing:

lapply(lst, function(x) length(x) <- max(lengths(lst)))
$a
[1] 2

$b
[1] 2

      

This is not the correct conclusion. Not

lapply(lst, function(x) length(x) <- max(lengths(x)))
 Error in lengths(x) : 'x' must be a list 

      

This will be a useful technique to understand well. Is there a way to express assignment in the form of an anonymous function?

+3


source to share


1 answer


By using anonymous functions, we only return the value of that function, not the value "x". We must indicate return(x)

or simply x

.



lapply(lst, function(x) {
                  length(x) <- max(lengths(lst))
                  x})
#$a
#[1]  1 NA

#$b
#[1] 2 3

      

+1


source







All Articles