Menu
Coddy logo textTech

グループの集計

CoddyのRジャーニー「ロジックとフロー」セクションの一部。レッスン 40/64。

tapply(values, groups, f)は値をグループ化し、1回の呼び出しですべてのグループにfを適用します。これはsapply(split(values, groups), f)と同じ結果になります:

amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
print(tapply(amounts, category, sum))
print(tapply(amounts, category, max))

出力:

food  fun rent 
  40   40   20 
food  fun rent 
  30   40   20 

結果にはグループ名が並べ替えられた順序で付けられるため、[[ ]] で1つのグループを読み取り、names() でグループ名を一覧表示します。

amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
avg <- tapply(amounts, category, mean)
print(avg[["food"]])
print(names(avg))

出力:

[1] 20
[1] "food" "fun"  "rent"

要約関数は自分で定義できます。ここでは、各グループで25を超える注文の数を数えています。

amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
print(tapply(amounts, category, function(v) sum(v > 25)))

出力:

food  fun rent 
   1    1    0 

結果は名前付きベクトルなので、sort() と which.max() で最大のグループを見つけられます。which.max() は同じ値がある場合、最初の値を返します。

amounts <- c(10, 20, 30, 40, 5)
category <- c("food", "rent", "food", "fun", "rent")
totals <- tapply(amounts, category, sum)
print(names(totals)[which.max(totals)])
print(names(sort(totals, decreasing = TRUE)))

出力:

[1] "food"
[1] "food" "fun"  "rent"
challenge icon

チャレンジ

簡単

city_report(cities, temps)を完成させてください。都市ごとに1行をアルファベット順で返します。例:oslo: avg 4.5, max 9。平均気温は小数第1位に丸め、最高気温も含めます。その後、平均気温が最も高い都市(平均気温が同じ場合はアルファベット順で最初の都市)の前にWarmest: を付けて追加します。

提供されたコードは、都市と気温を同じ長さのカンマ区切りの2行として読み取り、返された各行を出力します。

自分で試してみよう

city_report <- function(cities, temps) {
  # ここにコードを書いてください
  character(0)
}

# 提供された入出力コード:そのままにしておいてください
input <- suppressWarnings(readLines(file("stdin")))
cat(city_report(strsplit(input[1], ",")[[1]], as.numeric(strsplit(input[2], ",")[[1]])), sep = "\n")
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン

自分で練習してみよう: Rオンラインコンパイラ