【发布时间】:2016-11-23 22:09:28
【问题描述】:
在过去的几个小时里,我撞到了头,但仍然无法解决这个问题......
我正在尝试编写一个 R 函数,该函数将 dataframe name 和 column name 作为变量,并尝试返回具有指定列的所有不同值的 dataframe , 减去任何 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)
}
【问题讨论】:
-
我相信你需要
lazyeval::interp。看答案here