我想运行一个函数来测试数据集中是否存在一个值。我一直在寻找答案,后来找到了一种解决方法,但它并不那么整洁,我很好奇为什么我最初的尝试失败了。
这是一个简化的数据集
df <- structure(list(country = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("IRE","USA"),
class = "factor"), year = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("1990", "1995", "2000"),
class = "factor")), class = "data.frame", row.names = c(NA, -6L))
> df
country year
1 IRE 1990
2 IRE 1995
3 IRE 2000
4 USA 1990
5 USA 1995
6 USA 2000
Run Code Online (Sandbox Code Playgroud)
1如果存在特定的国家/地区代码和年份,我希望我的函数返回a,0否则返回。这是工作代码:
myFunc <- function(x,y){
p.ans <- df %>% filter(year == y)
ifelse(x %in% p.ans$country, …Run Code Online (Sandbox Code Playgroud)