JM_44
JM_44

Reputation: 43

Substract passed object name from a function argument

I have a question about substr, but I don´t know if its what I need to use. I have simplified the example to the minimum, so I only need the result on this to duplicate it in a function and loop through it.

Imagine you have a date frame ("House"), but inside the function, you have to refer at it as input. As there will be many Data Frames going through it an it can´t be called "House" specifically.

So, Data Frame "House". Inside the function, get the name of input. But then, I want to compare the three first letters of the Data Frame name with "Hou". If it´s TRUE, it will return some value, if it´s false return another value.

I have tried but I can´t figure it out. I don´t know if someone would be able to help me or my question will fall in a black spot forever.

Any help would be usefull. I need the answeer to be [1] TRUE.

House <- data.frame("SN" = 1:2, "Country" = c("Spain","France"), "Name" = c("John","Dora"))

input <- House

((substr("input", start=1, stop=3) == "Hou"))

[1] FALSE

Is there any way, to make this TRUE? I always get FALSE, as what it´s doing is compare "inp" with "Hou". 

If I take the quotes out,

House <- data.frame("SN" = 1:2, "Country" = c("Spain","France"), "Name" = c("John","Dora"))

input <- House

(substr(input, start=1, stop=3) == "Hou"))

[1] FALSE FALSE FALSE

Upvotes: 1

Views: 54

Answers (2)

pogibas
pogibas

Reputation: 28339

Pass your data frame as input and string to match as word.

foo <- function(input, word = "Hou") {
    name <- as.character(substitute(input))
    res <- substr(name, 1, 3) == word
    return(res)
}

House <- Duck <- data.frame()
foo(House)
[1] TRUE
foo(Duck)
[1] FALSE

Edit (respond to OP's comment):

foo <- function(input, word = "Hou") {
    name <- as.character(substitute(input))
    res <- substr(name, 1, 3) == word
    if (res) {
        nametitle <- input[1, 2] 
    } else {
        nametitle <- input[1, 3]
    }
    return(nametitle) 
}

Upvotes: 1

Rui Barradas
Rui Barradas

Reputation: 76402

Inside a function? The standard trick is deparse(substitute(.)).

fun <- function(input){
    inpName <- deparse(substitute(input))
    substr(inpName, start=1, stop=3) == "Hou"
}

fun(House)
#[1] TRUE

Upvotes: 0

Related Questions