我在R中有一个函数,它将矩阵作为输入并输出一个数据帧:
name X Y Z
Amy 25 40 78
Brad 67 78 90
..
我想在函数中添加一个参数,就像这样:
f(x,NameChoice) { #...matrix calcs #
return( subset( dataframe, Name = NameChoice ) )
}
以便f(x,Amy)
输出:
Amy 25 40 78
答案 0 :(得分:1)
试试这个(注意subset
的帮助页面明确建议不要在函数中使用它;
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
需要使用'['函数进行提取而不是subset
。
答案 1 :(得分:1)
我想你会期待这个:
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
答案 2 :(得分:1)
这是带有suspect
方法的代码。
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