이름 반복하기
Coddy R 여정의 논리와 흐름 섹션에 포함된 레슨. 64개 중 10번째.
for 루프는 names(x)를 순회하며 모든 키를 방문하고, x[[key]]는 해당 키의 값을 제공합니다:
scores <- c(ada = 91, bo = 78, cy = 85)
for (name in names(scores)) {
cat(name, "scored", scores[[name]], "\n")
}출력:
ada scored 91
bo scored 78
cy scored 85 항목은 추가된 순서를 유지합니다. 알파벳순으로 정렬하려면 sort(names(x))를 반복 처리하세요:
scores <- c(cy = 85, ada = 91, bo = 78)
for (name in sort(names(scores))) {
cat(name, scores[[name]], "\n")
}출력:
ada 91
bo 78
cy 85 입력을 반복하면서 조회 테이블을 업데이트하면 각 값이 나타나는 횟수를 셉니다. 단어가 처음 나타나면 1이 되고, 그 이후에는 1씩 증가합니다:
words <- c("red", "blue", "red", "green", "red")
counts <- c()
for (w in words) {
if (w %in% names(counts)) {
counts[w] <- counts[w] + 1
} else {
counts[w] <- 1
}
}
print(counts[["red"]])
print(names(counts))출력:
[1] 3
[1] "red" "blue" "green"출력 줄을 만들려면 루프 안에서 벡터에 줄을 모은 다음 마지막에 반환하거나 출력합니다:
scores <- c(ada = 91, bo = 78)
lines <- c()
for (name in names(scores)) {
lines <- c(lines, paste0(name, ": ", scores[[name]]))
}
cat(lines, sep = "\n")출력:
ada: 91
bo: 78챌린지
쉬움word_counts(words)를 완성하세요. 서로 다른 각 단어에 대해 한 줄씩 반환하고, 알파벳순으로 정렬하며 word: count 형식으로 작성하세요.
제공된 코드는 단어를 공백으로 구분된 한 줄로 읽고 반환된 각 줄을 출력합니다.
직접 해보기
word_counts <- function(words) {
# 여기에 코드를 작성하세요
character(0)
}
# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
cat(word_counts(strsplit(input[1], " ")[[1]]), sep = "\n")
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러