在过去的几个小时里我撞了头,但仍然无法解决这个问题......
我正在尝试编写一个 R 函数,该函数将数据框名称和列名称作为变量,并尝试返回一个数据框,其中包含指定列的所有不同值,减去任何 NA 或“N/A”值。
这是我的功能,
getDistinctColValues <- function(dataset, colname, removeNA = FALSE) {
colname <- as.name(colname)
retVector <- dataset %>% distinct_(colname)
# Not working!
if (removeNA == TRUE)
{
retVector <- filter_(retVector, colname != "N/A" | !is.null(colname))
}
return(retVector)
}
这是一个示例输出(请参阅 N/A):
> getDistinctColValues(dataTY, "SomeColumn", TRUE)
SomeColumn
1 BR
2 ET
3 SG
4 BV
5 N/A
6 MN
7 SP
此过滤器不起作用。na.omit 不起作用,因为有“N/A”字符串。我不清楚选择退出 NSE。我正在使用lazyeval 包,但没有深入了解它。
任何帮助将不胜感激。
解决方案(由@aosmith 指导):
getDistinctColValues <- function(dataset, colname, removeNA = FALSE) {
colname <- as.name(colname)
retVector <- dataset %>% distinct_(colname)
if (removeNA == TRUE)
{
filter_criteria <- interp(~v!="N/A", v=as.name(colname))
print(filter_criteria)
retVector <- retVector %>% filter_(filter_criteria)
}
return(retVector)
}