Reputation: 938
I have a function in R that takes as input a matrix and outputs a data frame with:
name X Y Z
Amy 25 40 78
Brad 67 78 90
..
I would like to add a parameter to the function that is text, like this:
f(x,NameChoice) { #...matrix calcs #
return( subset( dataframe, Name = NameChoice ) )
}
so that f(x,Amy)
would have output:
Amy 25 40 78
Upvotes: 0
Views: 2084
Reputation: 178
here is code with out suspect
method.
name val1 val2 val3 val4
abc 1 5 9 13
def 2 6 10 14
ghi 3 7 11 15
klm 4 8 12 16
fun<-function(x,NameChoice){
return(x[which(x$name==NameChoice),])
}
fun(df,'ghi')
result:
ghi 3 7 11 15
Upvotes: 1
Reputation: 178
i think you will expecting this:
df
name val1 val2 val3 val4
abc 1 5 9 13
def 2 6 10 14
ghi 3 7 11 15
klm 4 8 12 16
f<- function(x,NameChoice) {
return( subset( x, name == NameChoice ) )
}
f(df,'abc')
result:
name val1 val2 val3 val4
abc 1 5 9 13
Upvotes: 1
Reputation: 263342
Try this (noting that the help page for subset
specifically advises NOT to use it in a function);
func.in <- function(){cat("Enter colname and press enter:")
readLines(n = 1)} # No need for quotes since readline will "see" as character.
f <- function(inp) # enter the dataframe of interest
return( inp[ , func.in()])
}
#Example of use:
> f(inp)
Enter colname and press enter:
X
[1] 25 67
Need to use the '[' function for extraction rather than subset
.
Upvotes: 1