我经常遇到不得不在表中查找值的第一个实例的情况。例如,下面我必须找到按顺序排序的每个candy_type的第一个实例的颜色:
DatabaseMetaData meta = (DatabaseMetaData)
support.getConnection().getMetaData();
rs = meta.getTables("schema_name", null, null, new String[] { "TABLE" });
while (rs.next()) {
String tblName = rs.getString("TABLE_NAME");
System.out.println(tblName);
}
答案 0 :(得分:1)
您可以使用match
:
## Create sorted data.frame
d <- data.frame(
candy_type = c('A','A','B','B','C','C','C'),
sequence = c(2,1,1,2,2,3,1),
color = c('Red','Black','Green','Yellow','Orange','White','Purple')
)
d <- d[order(d[["candy_type"]], d[["sequence"]]), ]
## Works when candy_type is a factor column
## Otherwise, use unique() instead of levels()
first_of_type <- match(levels(d[["candy_type"]]), d[["candy_type"]])
first_of_type
# [1] 1 3 5
d[first_of_type, ]
# candy_type sequence color
# 2 A 1 Black
# 3 B 1 Green
# 7 C 1 Purple
答案 1 :(得分:1)
which.min()
是R等于idxmin()。两者都在数组中找到最小值,并返回第一个此类值的索引-如果有联系,则很有用。