How to Use With/Within Inside a Function

How to use with/within inside a function?

with is handy and improves readability in an interactive context but can hurt your brain in a programming context where you are passing things back and forth to functions and dealing with things in different environments. In general within R, using symbols rather than names is a sort of "semantic sugar" that is convenient and readable in interactive use but mildly deprecated for programming [e.g. $, subset]). If you're willing to compromise as far as using a name ("a") rather than a symbol (a) then I would suggest falling back to the simpler obj[[col]] rather than using with here ...

So, as a self-contained answer:

foo <- function(object,col) {
print(names(object))
print(object[[col]])
}

If you wanted to allow for multiple columns (i.e. a character vector)

foo <- function(object,col) {
print(names(object))
print(object[col])
}

edit: refraining from using subset with a function, at @hadley's suggestion

(this will print the answer as a data frame, even if a single column is selected, which may not be what you want).

How to use with() within a function in R?

In the first case the function is defined within the with so free variables in it will refer to the with but in the second case the function is defined outside the with so free variables will refer to objects in the environment where it is defined, not to those of the with. In general, it is best just not to do this in the first place but if you must then this redefines the environment of FUN so that it will work.

# not recommended but it will make the code work
withLapply = function(x, FUN){
with(x,
lapply(x, {environment(FUN) <- environment(); FUN}))
}
withLapply(dfTest, function(i){a})

proto

This also works since proto resets the environment of functions passed to it. Again it is probably better just to avoid all these complications.

library(proto)
withLapply = function(x, FUN){
with(x,
lapply(x, proto(FUN = FUN)[["FUN"]]))
}
withLapply(dfTest, function(i){a})

Execute WITH statement inside a function

You don't need the semicolon before the WITH in a TABLE-VALUED FUNCTION. Especially considering that you cannot even have multi-statements in a TVF, there's no reason for a statement delimiter to be present.

The correct form is CREATE FUNCTION (...) RETURNS TABLE AS RETURN <statement>

CREATE FUNCTION [dbo].[FN_INDICE_SPLIT]
(@sInputList VARCHAR(8000),@sDelimiter VARCHAR(8000),@INDICE INT)
RETURNS TABLE
AS RETURN
WITH OrderedOrders AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY item) AS RowNumber
from dbo.fnSplit(@sDelimiter, @INDICE)
)
select ITEM from OrderedOrders where RowNumber=@INDICE
GO

How does one use WITH within a Scalar Function?

First, I must say I agree with Larnu on this one - using a scalar function is probably not the best course of action you can take.

However, I wanted to show you that there's no problem using a common table expression in a user defined function - table valued or scalar.

The problem with the code you've shown is that you do have some syntax errors as well as some conceptual errors. A fixed version of that function (still using a cte) is this:

CREATE FUNCTION IsSumEqualToTen
(
@number1 INT,
@number2 INT
)
RETURNS BIT
AS
BEGIN
DECLARE @Result bit;

WITH AddNumbers(AddNumbers) AS
(
SELECT @number1 + @number2
)
SELECT @Result = CASE WHEN MAX(AddNumbers) = 10
THEN 1
ELSE 0
END
FROM AddNumberes;

RETURN @Result;
END

Notes:

  1. Each column in the cte result set must be named.
  2. A cte is treated as a table, you must take into consideration the fact that it might contain more than one row (even if it can only contain one, the compiler can't know that).
  3. scalar functions are not inlined, this means that you don't do return (body here) but body...; return scalarValue. Infact, this is how the official documentation looks like:
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name   
( [ { @parameter_name [ AS ][ type_schema_name. ] parameter_data_type
[ = default ] [ READONLY ] }
[ ,...n ]
]
)
RETURNS return_data_type
[ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
function_body
RETURN scalar_expression
END
[ ; ]

javascript function with in function in variable

How can I return g from that function?

You are returning g from "that function", assuming "that function" is f. Since f returns a function you are able to invoke the return value with f()(). It's pretty much the same as this:

var returnedFunction = f();
returnedFunction();

why not we can achieve this using f.g or something?

Because g is not a property of f. I'm not entirely sure what you're aiming for, but perhaps you wanted f to be a constructor, and instances of it to have a method g?

function f() {
// Constructor function
}
f.prototype.g = function () {
// Method
};
var myF = new f();
myF.g(); // Now `g` is accessible as a property of the instance

You could alternatively have intended g to be a static property of f:

function f() {
// JS has first-class functions so you can set properties on them
}
f.g = function () {
// Static method of `f`
};
f.g();

What is the difference between with and within in R?

The documentation is quite clear about the semantics and return values (and nicely matches the everyday meanings of the words “with” and “within”):

Value:

For ‘with’, the value of the evaluated ‘expr’. For ‘within’, the
modified object.

Since your code doesn’t modify anything inside baseball, the unmodified baseball is returned. with on the other hand doesn’t return the object, it returns expr.

Here’s an example where the expression modifies the object:

> head(within(cars, speed[dist < 20] <- 1))
  speed dist
1 1 2
2 1 10
3 1 4
4 7 22
5 1 16
6 1 10

how to use replace function with in clause in mysql

You can use LIKE, (but then its not going to use indexs)

SELECT GROUP_CONCAT(nm)
FROM xyz
WHERE CONCAT('|', abc, '|') LIKE CONCAT('%|', xyz.id, '|%');

nvl function with in clause

I doubt the id is NULL in the subquery. SO I would suggest:

with s3 as (
select s.id
from sysadm.students s.
where s.status = 'IN' and s.student_id = 24514
ORDER BY id
FETCH FIRST 3 ROWS ONLY
)
select . . .
where ci.id in (select id from s3) or
not exists (select 1 from s3);

This checks if your id is in the list -- or that the list is empty.

How do I call a function inside of another function?

function function_one() {    function_two(); // considering the next alert, I figured you wanted to call function_two first    alert("The function called 'function_one' has been called.");}
function function_two() { alert("The function called 'function_two' has been called.");}
function_one();


Related Topics



Leave a reply



Submit