data.table |C|R|U|D |group by

Published by onesixx on

Create data.table

create from scratch

생성과정은 data.frame과 같지만, 단, 한가지 Data.Frame은 Character를 factor로 변환하지만, data.table은 그냥 Character로 저장

R

create(convert) from data.frame

setDT()는 (사본을 만들거나 메모리 위치를 변경하지 않고) data.table을 만들 수 있다. (by reference) 즉, setDT() 함수로 사본을 만들지 않고, data.table 로 변환해 버린다.

R

Key setting

Key 세팅 하면, 해당 column으로 sorting 된다.

R

Alter table

Rename, Drop, Add Columns

R

Read  

J :: SELECT (columns Indexing)

결과가 벡터로~

하나의 컬럼을 사용할때는 

R

결과가 data.table로 

# c(“” )   # dot    # position

컬럼 선택시 숫자는 사용하지 않는것이 좋다.  (select *을 쓰지않는것과 같다.)

R

with=FALSE

Dataframe과 data.table의 차이

R

 vector scan,  일단 row수만큼의 TRUE/FALSE 벡터를 만들어 indexing한 후,   binary search     

data.frame에서 컬럼선택은 character 벡터를 사용하지만, data.table에서는 (character가 아닌) 실제 이름을 가진 List를 사용한다.
만약, 굳이 컬럼명을 character로 넘기려면, with=FALSE 옵션을 사용한다. (Default는 TRUE, 컬럼명은 variable)

R

위에서 with=FALSE를 사용하지 않으면 ,
theCols를 Character Vector(character/logical/integer)가 아닌, 컬럼명 variable로 해석하여 Error가 발생한다. 
j열에는 선택할 컬럼을 표기하는 컬럼명이 오기 때문에.

R

i :: Where (Rows subsetting)

Row accessing은 data.frame과 별반 다르지 않다. 

R

Subset/Filter row

R

Key를 세팅한 경우 

해당 Key의 값으로 row indexing가능

R

전체 찾기

R
sample data.table

각 요소에서 1인 값을 찾는 아래 수식은 data.table로 표현할수 없기 때문에, 일단 에러가 난다. 

R

하지만, assign은 가능하다. 

R

Group by

grouping illustrated

(By 또는 keyby) =>  by는 Group by 라고 생각하면 편하다. 
A,B을 기준으로 원래 data.table을 2개의 Group(sub data.table)으로 나눌수 있다. 

R
sample data.table

Ex> A가 a b c 3개의 그룹으로 나눌수 있으므로, 이를 기준으로 DT는 3개의 sub Group으로 나뉜다. 
        여기서 중요한 것은 나뉜 각 sub data.table은 계산시 .SD 라고 생각하면된다.

R
R

Group subsetting (Within Group Calculation)

ex> 각 그룹의 row 갯수

R

ex> 각 그룹의 random sample 1개씩

R

ex> 새로운 column 만들기

R
R

Order by 

order() 사용

R

sub Query (Chaining)

dt[…][…]

R

Update & Insert 

set.seed(666) 
DT <- data.table( A=rep(c("a","b","c"),each=2), B=c(1:3), C=sample(6), D=sample(6)) 

insert 는 새로운 컬럼명

R
   A B C D E
1: a 1 5 6 7
2: a 2 1 3 8
3: b 3 4 1 9
4: b 1 6 4 7
5: c 2 3 2 8
6: c 3 2 5 9

update는 기존의 column Name

dt[condition,`:=`(col2 = 123, col3 = 234, …)]

R
   A B C D E
1: a 1 5 6 7
2: a 2 1 3 8
3: b 3 4 1 1
4: b 1 6 4 1
5: c 2 3 2 8
6: c 3 2 5 9

update는 기존의 column Index

dt[condition,`:=`(col2 , 123)]

R
   A B C D E
1: a 1 5 6 7
2: a 2 1 3 8
3: b 3 4 1 1
4: b 1 6 4 1
5: c 2 3 2 8
6: c 3 2 5 9

update는 기존의 column Index

DT[condition, (2:4)`:=`lapply(.SD, f), .SDcols=2:4]
DT[         , (names(DT)[2:4]):= lapply(.SD, f), .SDcols = names(DT)[2:4]]
R
   A   B   C   D E
1: a 100 200 400 7
2: a 200 600 600 8
3: b 300 400 200 2
4: b 100 300 200 2
5: c 200 500 300 8
6: c 300 100 100 9

data.table remove comma and convert numeric in r

col_number <- colnames(ddFS)[..]
dd[ , lapply(.SD, function(x){str_replace_all(x,’,’,”) %>% as.numeric()}), .SDcols=col_number]

Categories: Reshaping

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x