我在R中编写了一个函数来返回数据框第一列的名称:
my_func <- function(table, firstColumnOnly = TRUE){
if(firstColumnOnly)
return(colnames(table)[1])
else
return(colnames(table))
}
如果我按这样调用函数:
my_func(fertility)<-"foo"
我收到以下错误:
Error in my_func(fertility, FALSE)[1] <- "foo" :
could not find function "my_func<-"
为什么我收到此错误?我可以毫无错误地做到这一点:
colnames(fertility)[1]<-"Country"
答案 0 :(得分:1)
好像你期待这样:
my_func(fertility)<-"foo"
R将理解:
colnames(table)[1] <- "foo" # if firstColumnOnly
或
colnames(table) <- "foo" # if !firstColumnOnly
不会。其中一个原因是colnames()
和colnames()<-
是两个不同的函数。第一个返回列名,第二个返回新名称。您的函数只能返回名称,而不能分配它们。
一种解决方法是使用colnames()<-
编写您的函数:
my_func <- function(table, rep, firstColumnOnly = TRUE){
if(firstColumnOnly) colnames(table)[1] <- rep
else colnames(table) <- rep
return(table)
}
测试
head(my_func(iris,"foo"))
foo Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa