Menu
Coddy logo textTech

추가 및 정렬

Coddy R 여정의 논리와 흐름 섹션에 포함된 레슨. 64개 중 45번째.

새 열 이름에 할당하면 열이 추가됩니다. 열 간의 산술 연산은 모든 벡터 산술 연산과 마찬가지로 행별로 작동합니다:

orders <- data.frame(item = c("tea", "jam", "oil"), qty = c(2, 5, 1), price = c(4, 2.5, 9))
orders$total <- orders$qty * orders$price
print(orders)

출력:

  item qty price total
1  tea   2   4.0   8.0
2  jam   5   2.5  12.5
3  oil   1   9.0   9.0

df[order(df$col), ]은 열을 기준으로 행을 정렬합니다. 왼쪽의 행 번호는 원래 행에 계속 연결되어 있습니다. 높은 값에서 낮은 값 순으로 정렬하려면 빼기 기호 또는 decreasing = TRUE를 사용하고, 동률인 경우 두 번째 키를 사용합니다:

orders <- data.frame(item = c("tea", "jam", "oil"), qty = c(2, 5, 1), price = c(4, 2.5, 9))
orders$total <- orders$qty * orders$price
print(orders[order(-orders$total, orders$item), c("item", "total")])

출력:

  item total
2  jam  12.5
3  oil   9.0
1  tea   8.0

새 열은 다른 열에서 만든 텍스트일 수 있습니다. sprintf()는 한 번에 전체 열에 적용됩니다:

orders <- data.frame(item = c("tea", "jam"), qty = c(2, 5), price = c(4, 2.5))
orders$label <- sprintf("%d x %s", orders$qty, orders$item)
print(orders$label)

출력:

[1] "2 x tea" "5 x jam"

rbind()는 동일한 열을 가진 한 행 데이터 프레임에서 행을 추가하고, head(df, n)은 처음 n개의 행을 유지합니다:

orders <- data.frame(item = c("tea", "jam"), qty = c(2, 5))
orders <- rbind(orders, data.frame(item = "oil", qty = 1))
print(nrow(orders))
print(head(orders[order(-orders$qty), ], 2))

출력:

[1] 3
  item qty
2  jam   5
1  tea   2
challenge icon

챌린지

쉬움

order_totals(df)를 완성하세요. df에는 item, qty, price 열이 있습니다. total 열(수량과 가격의 곱)을 추가하고, total이 높은 순서에서 낮은 순서로 행을 정렬하세요(total이 같은 항목은 알파벳순). 그런 다음 각 행마다 jam: 12.50 형식으로 한 줄씩 반환하며, total은 소수점 이하 두 자리까지 표시하세요.

제공된 코드는 read.csv(text = input)을 사용하여 입력에서 표를 읽습니다. 첫 번째 줄에는 열 이름이 들어 있고, 그다음 줄부터는 쉼표로 구분된 값이 포함된 각 행이 들어 있습니다. 코드는 반환된 각 줄을 출력합니다.

직접 해보기

order_totals <- function(df) {
  # 여기에 코드를 작성하세요
  character(0)
}

# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
df <- read.csv(text = input)
cat(order_totals(df), sep = "\n")
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리와 흐름의 모든 레슨

직접 연습해 보세요: 온라인 R 컴파일러