我试图在R中编写一个函数:
1)接收数据框和列名作为参数。 2)对数据框中的列执行操作。
func <- function(col, df)
{
col = deparse(substitute(col))
print(paste("Levels: ", levels(df[[col]])))
}
func(Col1, DF)
func(Col2, DF)
mapply(func, colnames(DF)[1:2], DF)
产量
> func(Col1, DF)
[1] "Levels: GREEN" "Levels: YELLOW"
> func(Col2, DF)
[1] "Levels: 0.1" "Levels: 1"
> mapply(func, colnames(DF)[1:2], DF)
Error in `[[.default`(df, col) : subscript out of bounds
两件事情 :
func
中,你将deparse(substitute(col))
应用于你期望不是字符串的对象col
。所以它适用于func(Col1, DF)
。但是在你的mapply()
调用中,你的参数colnames(...)
是一个字符串,所以它会产生错误。使用func('Col1', DF)
获得的错误相同。mapply()
调用中,所有参数都需要是向量或列表。所以你需要使用list(df, df)
,或者如果你不想复制,删除你的函数df
的参数func
。这是一个应该工作的替代方案:
func <- function(col, df)
{
print(paste("Levels: ", levels(df[,col])))
}
mapply(FUN = func, colnames(DF)[1:2], list(DF, DF))
请看一下@demarsylvain的最后评论 - 也许是你身边的复制粘贴错误,你应该做的:
func <- function(col,df) {
print(paste("Levels: ", levels(df[,col])))
}
mapply(FUN = func, c('Species', 'Species'), list(iris, iris))
你这样做了:
func <- function(col) {
print(paste("Levels: ", levels(df[,col])))
}
mapply(FUN = func, c('Species', 'Species'), list(iris, iris))
请upvote并接受@demarsylvain的解决方案,它的工作原理
编辑以解决您的评论:
要拥有任意列名列表的通用版本,您可以使用此代码,抱歉循环:)
func <- function(col,df) {
print(paste("Levels: ", levels(df[,col])))
}
cnames = colnames(iris)
i <- 1
l = list()
while(i <= length(cnames)) {
l[[i]] <- iris
i <- i + 1
}
mapply(FUN = func, cnames, l)