I am pretty new to R and this is probably an easy question so sorry about that! Let me present a simple case to make sure my question clearer
Let's say I create a list
testlist = list(a = 1:3, b = 4:6, c= 7:9)
print(testlist)
$a
[1] 1 2 3
$b
[1] 4 5 6
$c
[1] 7 8 9
I want to create a function where you input either a, b, or c and it returns the values associated with the selected element. What I tried was this
testfunc = function(element){
d = testlist$element
return(d)
}
No matter what you put as the element, the function returns NULL. How should I change the function such that whatever is inputted in (element) is put after the $?
CodePudding user response:
We can use [[
instead of $
testfunc = function(element){
d = testlist[[element]]
return(d)
}
-testing
> testfunc("a")
[1] 1 2 3