总的来说,我对 R 和编程很陌生,并且已经在以下几个小时内苦苦挣扎。
我正在尝试创建一个函数,它将一个 df 和一个列名作为变量,根据提供的列名过滤表并打印输出。
example_function <- function(df=df, col=col){
a <- df[col == 100,]
b <- filter(df, col == 100)
print(a)
print(b)
}
使用
example_function(df=example_df, col='percentage')
不起作用,两个变量都只返回列名而不返回数据行(尽管存在值 == 100)。使用
example_function(df=df, col=percentage)
,所以百分比在这里没有被引号包围,我得到:Error in
[.data.frame
(df, col == 100, ) : object 'percentage' not found
但是,当我运行
example_function(df=example_df, col=example_df$percentage)
时我得到了正确的结果,我的数据帧按预期返回,只有 example_df$percentage
的那些行等于 100。我真的希望能够将 df 作为一个变量传递,将列作为另一个变量传递,而无需键入
example_df$percentage
每次我都希望能够对许多不同的数据帧重复使用该函数,并且输入似乎是多余的。基于此,我然后修改了函数,认为我可以只使用
df$col
在函数中,它将评估为 example_df$percentage
并像上面那样工作:example_function <- function(df=df, col=col){
a <- df[df$col == 100,]
b <- filter(df, df$col == 100)
print(a)
print(b)
}
但是现在我在使用
example_function(df=example_df, col=percentage)
时遇到另一个错误或路过时col='percentage'
:Error in filter_impl(.data, quo) : Result must have length 19, not 0
是否有任何机构能够帮助我解决这个问题,或者为我指明正确的方向以了解为什么我正在做的事情不起作用?
非常感谢
这是我正在使用的数据框的一个示例(虽然我的真实数据框会有更多列,但我希望它不会对这个示例产生影响。)
name | percentage
-----------------------
tom | 80
john | 100
harry | 99
elizabeth| 100
james | 50
example_df <- structure(list(name = structure(c(5L, 4L, 2L, 1L, 3L), .Label = c("elizabeth",
"harry", "james", "john", "tom"), class = "factor"), percentage = c(80L,
100L, 99L, 100L, 50L)), .Names = c("name", "percentage"), class = "data.frame", row.names = c(NA,
-5L))
** 更新:我设法让它与以下一起工作:
example_function <- function(df=df, col=col){
a <- df[df[col] == 100,]
print(a)
}
路过
example_function(df=example_df, col='percentage')
最佳答案
第一排example_function
应该
a <- df[df[[col]] == 100,]
当你分解它时,
df[['names']] == 100
将为您提供与 df
的哪些行相对应的逻辑列表有一个 names
值为 100。但是 'names' == 100
是荒谬的:它总是错误的。
关于R:在自定义函数中将列名作为变量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47005768/