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.