열과 행
Coddy R 여정의 논리와 흐름 섹션에 포함된 레슨. 64개 중 43번째.
df$col과 df[["col"]]은 열을 일반 벡터로 반환하므로 모든 벡터 함수가 해당 열에서 작동합니다. [[ ]]은 변수에 저장된 열 이름을 허용합니다:
people <- data.frame(
name = c("ada", "bo", "cy"),
age = c(36, 22, 41),
city = c("london", "paris", "rome")
)
print(people$age)
print(mean(people$age))
col <- "city"
print(people[[col]])출력:
[1] 36 22 41
[1] 33
[1] "london" "paris" "rome" 대괄호는 행렬처럼 [row, column]을 사용합니다. 비어 있는 쪽은 모든 항목을 선택하며, 열은 이름으로 선택할 수 있습니다:
people <- data.frame(
name = c("ada", "bo", "cy"),
age = c(36, 22, 41),
city = c("london", "paris", "rome")
)
print(people[2, ])
print(people[, c("name", "city")])출력:
name age city
2 bo 22 paris
name city
1 ada london
2 bo paris
3 cy rome하나의 셀은 df[row, column]이며, 해당 셀에 값을 할당하면 값이 변경됩니다. 전체 열에 값을 할당하는 방식도 동일합니다:
people <- data.frame(
name = c("ada", "bo", "cy"),
age = c(36, 22, 41),
city = c("london", "paris", "rome")
)
print(people[3, "age"])
people[3, "age"] <- 42
people$city <- toupper(people$city)
print(people)출력:
[1] 41
name age city
1 ada 36 LONDON
2 bo 22 PARIS
3 cy 42 ROME행을 하나씩 살펴보려면 seq_len(nrow(df))을 반복하고, 각 셀을 df[i, "col"] 또는 df$col[i]로 읽습니다:
people <- data.frame(
name = c("ada", "bo", "cy"),
age = c(36, 22, 41),
city = c("london", "paris", "rome")
)
for (i in seq_len(nrow(people))) {
cat(people$name[i], "lives in", people[i, "city"], "\n")
}출력:
ada lives in london
bo lives in paris
cy lives in rome 챌린지
쉬움person_card(df, i)를 완성하세요. 행 i에 대해 열마다 한 줄씩 반환하세요. 각 줄에는 열 이름과 해당 행의 값이 name: bo 형식으로 표시되며, 열의 순서를 따릅니다.
제공된 코드는 read.csv(text = input)을 사용하여 입력에서 표를 읽습니다. 첫 번째 줄에는 열 이름이 있고, 그 다음 줄들은 쉼표로 구분된 값이 있는 각 행입니다. 입력의 마지막 줄에는 i가 있으며, 코드는 반환된 각 줄을 출력합니다.
직접 해보기
person_card <- function(df, i) {
# 여기에 코드를 작성하세요
character(0)
}
# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
df <- read.csv(text = input[-length(input)])
i <- as.numeric(input[length(input)])
cat(person_card(df, i), sep = "\n")
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러