It is unclear after reading the comments.
library(dplyr)
df %>%
group_by(zone) %>%
filter(population==min(population)) %>%
#ungroup() %>% #if you don't need zone
select(name)
# zone name
# 1 3 American-Samoa
# 2 1 Andorra
# 3 2 Angola
Update
devtools::install_github("hadley/dplyr")
devtools::install_github("hadley/lazyeval")
library(dplyr)
library(lazyeval)
fun2 <- function(grp, Column, grpDontShow=TRUE){
stopifnot(is.numeric(df[,grp]) & Column %in% colnames(df))
df1 <- df %>%
group_by_(grp) %>%
filter_(interp(~x==min(x), x=as.name(Column)))%>%
arrange(name) %>%
filter(row_number()==1) %>%
select(name)
if(grpDontShow){
ungroup(df1) %>%
select(name)
}
else {
df1
}
}
fun2("zone", "population", TRUE)
# Source: local data frame [3 x 1]
# name
#1 Andorra
#2 Angola
#3 American-Samoa
fun2("zone", "landmass", FALSE)
#Source: local data frame [3 x 2]
#Groups: zone
# zone name
#1 1 Albania
#2 2 Angola
#3 3 American-Samoa
fun2("ozone", "landmass", FALSE)
#Error in `[.data.frame`(df, , grp) : undefined columns selected
fun2("name", "landmass", FALSE)
#Error: is.numeric(df[, grp]) & Column %in% colnames(df) is not TRUE
Update2
If you need a function using base R
funBase <- function(grp, Column, grpDontShow = TRUE) {
stopifnot(is.numeric(df[, grp]) & Column %in% colnames(df))
v1 <- c(by(df[, c(Column, "name")], list(df[, grp]),
FUN = function(x) sort(x[,2][x[, 1] == min(x[, 1],
na.rm = TRUE)])[1]))
if (grpDontShow) {
data.frame(name = v1, stringsAsFactors = FALSE)
}
else {
setNames(data.frame(as.numeric(names(v1)),
v1, stringsAsFactors = FALSE), c(grp, "name"))
}
}
funBase("zone", "landmass")
# name
#1 Albania
#2 Angola
#3 American-Samoa
funBase("zone", "population", FALSE)
# zone name
#1 1 Andorra
#2 2 Angola
#3 3 American-Samoa
data
df <- structure(list(name = c("Afghanistan", "Albania", "Algeria",
"American-Samoa", "Andorra", "Angola"), landmass = c(5L, 3L,
4L, 6L, 3L, 4L), zone = c(1L, 1L, 1L, 3L, 1L, 2L), area = c(648L,
29L, 2388L, 0L, 0L, 1247L), population = c(16L, 3L, 20L, 0L,
0L, 7L)), .Names = c("name", "landmass", "zone", "area", "population"
), class = "data.frame", row.names = c("1", "2", "3", "4", "5",
"6"))