私はデータフレームを持っています。
2 列目の値ごとに 1 列目の最小値を見つける必要があります。しかし、1 列目にある最小値と同じ行から 3 列目に値を返す必要があります。
最初の部分は次のように解決されるようですtapply(1,2, min)
しかし、同じ行を 3 列目に渡す方法は?
より複雑なタスクは、最小値が 1 列目で一意でない場合です。次に、(複数の中から) 名前をアルファベット順に選択し、3 列目の同じ行から対応する値を見つける必要があります。
コメントを読んだ後では不明です。
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
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
を使用する関数が必要な場合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
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"))
再現可能な例は、質問を完全に理解するのに役立ちます。
ただし、これには ave を使用できると思います。
a<-c(1:10)
b<-c(rep(1,3),rep(2,4),rep(3,3))
c<-c(101:110)
df<-cbind(a,b,c)
を与える
df
a b c
[1,] 1 1 101
[2,] 2 1 102
[3,] 3 1 103
[4,] 4 2 104
[5,] 5 2 105
[6,] 6 2 106
[7,] 7 2 107
[8,] 8 3 108
[9,] 9 3 109
[10,] 10 3 110
したがって、a と b の最小値を見つけて、対応する c を保持します。
rows<-df[which(ave(df[,1],df[,2],FUN=function(x) x==min(x))==1),]
を与える
rows
a b c
[1,] 1 1 101
[2,] 4 2 104
[3,] 8 3 108