"R 그룹별 합 구하기"의 두 판 사이의 차이

잔글 (봇: 자동으로 텍스트 교체 (-<source +<syntaxhighlight , -</source> +</syntaxhighlight>))
2번째 줄: 2번째 줄:
;R 그룹별 합 구하기
;R 그룹별 합 구하기
* 대략 "SELECT fruit, SUM(ea) FROM df GROUP BY fruit"
* 대략 "SELECT fruit, SUM(ea) FROM df GROUP BY fruit"
<source lang='r' notebook>
<syntaxhighlight lang='r' notebook>
df <- read.csv( header=T, stringsAsFactors=F, text="
df <- read.csv( header=T, stringsAsFactors=F, text="
day,fruit,ea
day,fruit,ea
13번째 줄: 13번째 줄:
")
")
df
df
</source>
</syntaxhighlight>


==방법 1: aggregate ★==
==방법 1: aggregate ★==
<source lang='r' notebook>
<syntaxhighlight lang='r' notebook>
aggregate(ea ~ fruit, df, sum)
aggregate(ea ~ fruit, df, sum)
</source>
</syntaxhighlight>


==방법 2: tapply==
==방법 2: tapply==
<source lang='r' notebook>
<syntaxhighlight lang='r' notebook>
tapply(df$ea, df$fruit, sum)
tapply(df$ea, df$fruit, sum)
</source>
</syntaxhighlight>


==방법 3: sqldf==
==방법 3: sqldf==
<source lang='r' notebook>
<syntaxhighlight lang='r' notebook>
library(sqldf)
library(sqldf)
sqldf("SELECT fruit, SUM(ea) AS s FROM df GROUP BY fruit")
sqldf("SELECT fruit, SUM(ea) AS s FROM df GROUP BY fruit")
</source>
</syntaxhighlight>


==같이 보기==
==같이 보기==

2021년 4월 9일 (금) 20:30 판

1 개요

R 그룹별 합 구하기
  • 대략 "SELECT fruit, SUM(ea) FROM df GROUP BY fruit"
df <- read.csv( header=T, stringsAsFactors=F, text="
day,fruit,ea
2019-06-01,apple,1
2019-06-11,apple,1
2019-06-21,banana,2
2019-07-01,apple,3
2019-07-11,banana,4
2019-08-25,orange,2
")
df

2 방법 1: aggregate ★

aggregate(ea ~ fruit, df, sum)

3 방법 2: tapply

tapply(df$ea, df$fruit, sum)

4 방법 3: sqldf

library(sqldf)
sqldf("SELECT fruit, SUM(ea) AS s FROM df GROUP BY fruit")

5 같이 보기

6 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}