Programming

data.table에서 : =를 사용하여 여러 열을 그룹별로 지정

procodes 2020. 7. 27. 08:02
반응형

data.table에서 : =를 사용하여 여러 열을 그룹별로 지정


data.table?를 사용하여 여러 열에 할당하는 가장 좋은 방법은 무엇입니까 ? 예를 들면 다음과 같습니다.

f <- function(x) {c("hi", "hello")}
x <- data.table(id = 1:10)

다음과 같이하고 싶습니다 (물론이 구문이 올바르지 않습니다).

x[ , (col1, col2) := f(), by = "id"]

그리고 그것을 확장하기 위해 변수에 이름이 저장된 많은 열이있을 수 있습니다 (예 col_names:).

x[ , col_names := another_f(), by = "id", with = FALSE]

이와 같은 작업을 수행하는 올바른 방법은 무엇입니까?


이것은 R-Forge의 v1.8.3에서 작동합니다. 강조해 주셔서 감사합니다!

x <- data.table(a = 1:3, b = 1:6) 
f <- function(x) {list("hi", "hello")} 
x[ , c("col1", "col2") := f(), by = a][]
#    a b col1  col2
# 1: 1 1   hi hello
# 2: 2 2   hi hello
# 3: 3 3   hi hello
# 4: 1 4   hi hello
# 5: 2 5   hi hello
# 6: 3 6   hi hello

x[ , c("mean", "sum") := list(mean(b), sum(b)), by = a][]
#    a b col1  col2 mean sum
# 1: 1 1   hi hello  2.5   5
# 2: 2 2   hi hello  3.5   7
# 3: 3 3   hi hello  4.5   9
# 4: 1 4   hi hello  2.5   5
# 5: 2 5   hi hello  3.5   7
# 6: 3 6   hi hello  4.5   9 

mynames = c("Name1", "Longer%")
x[ , (mynames) := list(mean(b) * 4, sum(b) * 3), by = a]
#     a b col1  col2 mean sum Name1 Longer%
# 1: 1 1   hi hello  2.5   5    10      15
# 2: 2 2   hi hello  3.5   7    14      21
# 3: 3 3   hi hello  4.5   9    18      27
# 4: 1 4   hi hello  2.5   5    10      15
# 5: 2 5   hi hello  3.5   7    14      21
# 6: 3 6   hi hello  4.5   9    18      27


x[ , get("mynames") := list(mean(b) * 4, sum(b) * 3), by = a][]  # same
#    a b col1  col2 mean sum Name1 Longer%
# 1: 1 1   hi hello  2.5   5    10      15
# 2: 2 2   hi hello  3.5   7    14      21
# 3: 3 3   hi hello  4.5   9    18      27
# 4: 1 4   hi hello  2.5   5    10      15
# 5: 2 5   hi hello  3.5   7    14      21
# 6: 3 6   hi hello  4.5   9    18      27

x[ , eval(mynames) := list(mean(b) * 4, sum(b) * 3), by = a][]   # same
#    a b col1  col2 mean sum Name1 Longer%
# 1: 1 1   hi hello  2.5   5    10      15
# 2: 2 2   hi hello  3.5   7    14      21
# 3: 3 3   hi hello  4.5   9    18      27
# 4: 1 4   hi hello  2.5   5    10      15
# 5: 2 5   hi hello  3.5   7    14      21
# 6: 3 6   hi hello  4.5   9    18      27

with인수를 사용하는 이전 버전 (가능한 경우이 인수를 권장하지 않음) :

x[ , mynames := list(mean(b) * 4, sum(b) * 3), by = a, with = FALSE][] # same
#    a b col1  col2 mean sum Name1 Longer%
# 1: 1 1   hi hello  2.5   5    10      15
# 2: 2 2   hi hello  3.5   7    14      21
# 3: 3 3   hi hello  4.5   9    18      27
# 4: 1 4   hi hello  2.5   5    10      15
# 5: 2 5   hi hello  3.5   7    14      21
# 6: 3 6   hi hello  4.5   9    18      27

다음과 같은 속기 표기법이 유용 할 수 있습니다. 모든 크레딧은 Andrew Brooks, 특히이 기사에 갑니다.

dt[,`:=`(avg=mean(mpg), med=median(mpg), min=min(mpg)), by=cyl]

참고 URL : https://stackoverflow.com/questions/11680579/assign-multiple-columns-using-in-data-table-by-group

반응형