Home > Enterprise >  How can I make my function access variables in this dataframe?
How can I make my function access variables in this dataframe?

Time:01-16

Taking into consideration the following database (called data), I want to make a function that retrieves the first "Start" position of a given "Letter". I want my function to take the dataframe and Letter as inputs. And I'd like to do this without the use of libraries.

Letter Start End
A 1 2
A 3 3
A 2 4
B 4 5
B 6 1
B 2 6
C 4 8
C 9 3
C 7 3

I thought the first step should be to subset the specific "Letter" I want to get the "Start" position for:

newdata <- subset(data, data == "A")

This resulted in a dataframe that's specific for the Letter A:

Letter Start End
A 1 2
A 3 3
A 2 4

Step two should be to index the subsetted dataframe for the first start position:

newdata[1,2] Output: 1

It worked therefore I made a function based on the aforementioned steps where x is a named dataframe and y is the variable to be selected for:

getFirstLetter <- function(x, y){ newdata <- subset(x, x == "y") return(newdata[1,2]) }

Tested the function but got NA: getFirstLetter(data, A) Output: NA

Troubleshooting code: getFirstLetter(data, "A") Output: NA

I'd appreciate some guidance on why my function isn't returning the intended output. Thanks.

CodePudding user response:

You can use as.character(substitute()):

getFirstLetter <- function(x, y) { 
  y <- as.character(substitute(y))
  newdata <- subset(x, Letter == y)
  newdata[1,2]
}

getFirstLetter(data, A)
# 1

A slightly more succinct approach would be to index into x using match():

getFirstLetter <- function(x, y) { 
  y <- as.character(substitute(y))
  x[[match(y, x$Letter), "Start"]]
}

CodePudding user response:

library(tibble)

df <- tibble::tribble(
  ~Letter, ~Start, ~End,
      "A",     1L,   2L,
      "A",     3L,   3L,
      "A",     2L,   4L,
      "B",     4L,   5L,
      "B",     6L,   1L,
      "B",     2L,   6L,
      "C",     4L,   8L,
      "C",     9L,   3L,
      "C",     7L,   3L
  )
getFirstLetter <-  function(df, letter){
  newdata <- subset(df, Letter == letter)[1,2] 
  return(newdata) 
}

getFirstLetter(df = df, letter = "A")
  • Related