2
Field1, Field2 및 Value의 3 개 열이있는 데이터 테이블이 있습니다. Field2의 각 속성에 대해 값의 최대 합계에 해당하는 Field1의 특성을 찾고 싶습니다 (즉, 데이터 테이블에 여러 개의 Field1/Field2 행이 있음).가장 큰 합계를 가진 R 데이터 테이블 선택 항목
내가 이것을 시도 할 때 : x[,.(Field1 = Field1[which.max(sum(Value))]),.(Field2)]
값의 최대 합계에 해당하는 행보다는 각 Field2에 대해 첫 번째 Field1 행을 얻는 것처럼 보입니다.
값의 합계, 총 행 수 및 Field2의 값 필드에서 가장 큰 합계에 해당하는 Field1 값을 모두 제공하려면 어떻게해야합니까?
아래 코드는 재생산 코드입니다.
library(data.table)
#Set random seed
set.seed(2017)
#Create a table with the attributes we need
x = data.table(rbind(data.frame(Field1 = 1:12,Field2 = rep(1:3, each = 4), Value = runif(12)),
data.frame(Field1 = 1:12,Field2 = rep(1:3, each = 4), Value = runif(12))))
#Let's order by Field2/ Field1/Value
x = x[order(Field2,Field1,Value)]
#Check
print(x)
# This works, but requires 2 steps which can complicate things when needing
# to pull other attributes too.
(x[,.(Value = sum(Value)),.(Field2,Field1)][,.SD[which.max(Value)],.(Field2)])
#This instead provides the row corresponding to the largest Value.
(x[,.(Field1 = Field1[which.max(Value)]),.(Field2)])
# This is what I was ideally looking for but it only returns the first row of the attribute
# regardless of the value of Value, or the corresponding sum.
(x[,.(Field1 = Field1[which.max(sum(Value))]),.(Field2)])
# This works but seems clumsy
(x[,
.SD[, .(RKCNT=length(.I),TotalValue=sum(Value)), .(Field1)]
[,.(RKCNT = sum(RKCNT), TotalValue = sum(TotalValue),
Field1 = Field1[which.max(TotalValue)])],
.(Field2)])
동점이 없다고 가정하면 합계로 정렬 한 다음 '고유'를 사용할 수 있습니다. x [, lapply (.SD, sum), by =. (Field2, Field1)] [order (Field2, - Value), 고유 (.SD, by = "Field2")]'. 어딘가에서이 속임수가 있다고 생각합니다. – Frank
당신의 주된 질문이 아니지만 주문을위한 data.table 관용구는'setorder'를 사용하는 것입니다 "참조에 의한 data.table의 빠른 행 재정렬" – dww