Python·R의 자료형·함수·실행 환경Python and R: types, functions and execution environments
이름과 값에서 실제 자료 함수·오류·결측·새 프로세스 재현까지From names and values to actual-data functions, errors, missingness and fresh-process reproduction
실습 6종 · 풀이 포함 연습문제 60개6 labs · 60 exercises with solutions
기초Foundations
1. 숫자를 계산하기 전에 컴퓨터에 무엇을 맡길까1. What should the computer do before we ask for a number?
종이에 적힌 2와 따옴표 안의 “2”는 사람 눈에는 비슷합니다. 그런데 계산기는 앞의 값을 수로 더하고 뒤의 값을 문자로 이어 붙일 수 있습니다. 잘못 읽은 자료를 아주 빠르게 처리하면 틀린 답도 아주 빠르게 나옵니다. 이 장에서는 복잡한 분석보다 먼저, 컴퓨터가 어떤 값을 어떤 종류로 보관하고 어떤 순서로 바꾸는지 배웁니다.
실제 Card 자료에는 사람 기록 3,613행이 있지만 가용 로그 임금은 3,010개입니다. 나머지 603개를 숫자 0으로 바꾼 뒤 평균을 내는 일과, 미관측 표식으로 남기고 가용값의 분모를 쓰는 일은 서로 다른 계산입니다. 짧은 함수 하나에도 관측 단위·자료형·결측 규칙이 들어갑니다. 뒤에서 실제 파일을 읽어 이 차이를 직접 추적합니다.
학습 목표는 코드를 외우는 것이 아닙니다. “이 줄의 입력은 무엇인가, 어떤 값이 어떤 이름에 연결되는가, 무엇을 반환하는가, 오류가 나면 어디에서 멈추는가”를 설명하는 것입니다. 한 줄의 결과를 먼저 예상하고, 실제 실행 기록을 확인한 다음, 내려받은 파일을 새 프로세스에서 실행하세요.
The number 2 and the text “2” look similar to a person. A program can add the former numerically and concatenate the latter as text. Fast processing of a misread value produces a wrong answer quickly. Before advanced analysis, learn which values the computer stores, what types they have and how instructions change them.
The actual Card source contains 3,613 person records but only 3,010 available log wages. Replacing the remaining 603 with numeric zero differs from retaining missing markers and using the available-value denominator. Even a short function embodies an observation unit, a type choice and a missingness rule. We will trace those decisions on the retained actual files.
The goal is not memorizing syntax. Explain each line’s input, the value bound to a name, its returned result and where an error occurs. Predict an output, inspect the actual recorded execution and then run the downloaded file in a fresh process.
기초Foundations
2. 새 프로세스에서 시작하고 실행한 버전을 기록한다2. Start a fresh process and record the runtime version
프로세스는 지금 실행 중인 프로그램의 한 인스턴스입니다. 같은 컴퓨터에서도 Python 창을 새로 열면 다른 창에서 만든 이름이 자동으로 생기지 않습니다. R도 마찬가지로, 새 세션이 이전 작업 공간을 복원하지 않도록 시작하면 과거 이름에 기대지 않고 코드를 확인할 수 있습니다. “파일이 있다”와 “그 파일을 실행해 값이 메모리에 있다”는 다릅니다.
이 장의 보관 실행은 Python 3.12.14와 R 4.5.1에서 수행했습니다. 최신 버전이라는 뜻은 아닙니다. 실제로 실행한 버전과 코드·입력의 해시를 함께 기록한 것입니다. 설치된 버전이 다르면 먼저 버전 문자열을 적고, 출력이나 오류 문구가 다른 이유를 조사하세요. 명령 이름을 찾지 못했다는 운영체제 메시지는 코드의 수학이 틀렸다는 증거가 아닙니다.
python --version
Rscript --version
다운로드한 교재 폴더에서 다음 두 파일을 각각 실행하면 평균 함수가 가정 자료 2,4,6의 평균을 출력합니다. 명령을 실행하는 창과 명령 뒤 파일 경로를 구별하세요. R의 --vanilla는 시작 파일·저장 작업 공간 등에 덜 의존하는 재현 출발점입니다. 자세한 폴더·설치·편집기 작업은 다음 장에서 이어갑니다.
먼저 두 언어 중 하나만 실행해도 됩니다. 실습 화면의 기록은 준비된 코드가 실제로 낸 결과를 보여 주지만, 현재 브라우저 안에서 Python이나 R 프로세스를 새로 실행하는 것은 아닙니다.
A process is one running instance of a program. A fresh Python process does not automatically contain names created in another window. Starting R without restoring an old workspace likewise tests code without relying on yesterday’s objects. A file existing on disk differs from that file having executed and created values in memory.
The archived runs used Python 3.12.14 and R 4.5.1. These are recorded runtime versions, not a claim to use the newest release. Runtime metadata accompany code and input hashes. If your version differs, record it before investigating output or error-message differences. An operating-system “command not found” message is not evidence that the mathematics is wrong.
python --version
Rscript --version
From the downloaded chapter directory, run either file below. Its mean function prints the mean of toy values 2, 4 and 6. Distinguish the command window from the file path passed to it. R’s --vanilla reduces dependence on startup files and saved workspaces. The next chapter develops folders, installation and editing workflows.
Choose one language initially. The browser displays archived results of actual runs; it does not start a live Python or R process.
기초Foundations
3. 값·식·출력의 세 단계를 나눈다3. Separate a value, an expression and displayed output
3은 코드에 직접 쓴 값이고, 3 + 2는 값을 계산하는 식입니다. print(3 + 2)는 계산한 결과를 화면으로 내보냅니다. 종이에 쓴 3+2를 머릿속에서 계산하는 일과 그 답을 칠판에 적는 일을 나누어 생각하면 쉽습니다.
Python
print(3 + 2)
print("3" + "2")
R
print(3 + 2)
print(paste0("3", "2"))
첫 출력은 5이고 둘째는 문자 “32”입니다. 두 번째 계산을 수치의 합 5로 읽지 않습니다. R은 보통 출력 앞에 [1] 같은 위치 표식을 붙입니다. 이것은 추가 관측값이나 배열 원소가 아니라 출력 형식의 안내입니다.
대화형 창은 마지막 식의 값을 자동으로 보여 줄 수 있지만, 스크립트 파일의 출력 규칙은 다를 수 있습니다. 재현 코드에서는 무엇을 확인할지 print 또는 cat으로 분명히 표시합니다. 화면에 숫자가 보이지 않는다는 사실만으로 계산이 수행되지 않았다고 판단하지 않습니다.
3 is a value written directly in code. 3 + 2 is an expression computing a value. print(3 + 2) displays the result. Think of calculating an answer mentally and writing that answer on a board as separate actions.
Python
print(3 + 2)
print("3" + "2")
R
print(3 + 2)
print(paste0("3", "2"))
The first output is 5; the second is text “32”, not the numeric sum five. R often prefixes printed values with an index such as [1]. It is a display annotation, not another observation or vector element.
An interactive console may automatically display its last expression, whereas a script has its own output behavior. Reproduction code explicitly uses print or cat to show what we inspect. No visible number does not by itself establish that no calculation happened.
기초Foundations
4. 변수는 값에 붙인 이름이고 할당은 그 연결을 바꾼다4. A variable is a binding between a name and a value
이름은 답을 다시 쓰기 위한 손잡이입니다. count = 3 또는 count <- 3은 이름 count를 값 3에 연결합니다. 이때 등호 모양이 있다고 해서 수학의 모든 방향으로 성립하는 방정식을 선언하는 것은 아닙니다. 오른쪽을 먼저 계산한 뒤 왼쪽 이름에 할당합니다.
이 숫자 예제의 마지막 값은 9와 3입니다. copy를 만들 때의 값 3이 연결되었기 때문입니다. count가 바뀔 때마다 copy도 자동으로 다시 계산되는 스프레드시트 수식이 아닙니다. 나중에 다루는 변경 가능한 객체의 공유 문제까지 “모든 할당은 독립 복사”라고 일반화하지는 않습니다.
count = count + 1은 오른쪽의 기존 값을 읽어 1을 더한 후 같은 이름에 새 값을 연결합니다. 새 프로세스에서 기존 이름을 만들지 않았다면 읽을 값이 없어 오류가 납니다. 이름은 대소문자를 구별하므로 count와 Count도 다릅니다.
A name is a handle for reusing a value. count = 3 or count <- 3 binds the name to three. Assignment is not a mathematical equation valid in both directions. Evaluate the right side, then bind its result to the left-side name.
The final values in this numeric example are nine and three. copy received the earlier value. It is not a spreadsheet formula automatically recomputed whenever count changes. Do not generalize this numeric example into the claim that every assignment independently copies every possible mutable object.
count = count + 1 first reads the existing value and adds one, then rebinds the same name. If the name has not been created in a fresh process, reading it raises an error. Names are case-sensitive: count and Count differ.
기초Foundations
5. 할당·같음 비교·조건을 구별한다5. Distinguish assignment, equality comparison and a condition
친구에게 “이 상자에 3이라고 적어”라고 부탁하는 일과 “이 상자 값이 3이니?”라고 묻는 일은 다릅니다. 할당은 이름의 연결을 만들고, ==는 두 값의 같음을 비교해 참·거짓을 계산합니다. 초보 예제에서는 R의 할당을 <-로 적어 비교와 눈으로 구분합니다.
Python
x = 3
print(x == 3, x > 4)
R
x <- 3
print(x == 3); print(x > 4)
결과는 각각 참과 거짓입니다. Python은 True/False, R은 TRUE/FALSE로 표시합니다. 화면 모양이 다른 것이 다른 관측값을 얻었다는 뜻은 아닙니다. 논리값은 나중에 어느 행을 고를지 결정하는 조건으로 쓰입니다.
“어떤 값이든 자기 자신과 비교하면 참”이라고 외우지는 마세요. 계산 불능 수치 NaN과 미관측 표식에는 별도 규칙이 있습니다. 또한 십진 소수의 기계 저장 때문에 계산 결과가 기대한 십진 값과 정확히 같지 않을 수 있습니다. 이 장 뒤에서 실제 출력으로 확인합니다.
“Put three in this box” differs from “Is the box’s value three?” Assignment creates a binding; == computes an equality comparison. We use <- for beginner R assignments to make the distinction visible.
Python
x = 3
print(x == 3, x > 4)
R
x <- 3
print(x == 3); print(x > 4)
The results are true and false. Python prints True/False; R prints TRUE/FALSE. Different display conventions do not imply different observations. Logical values later determine which records to select.
Do not assume every value equals itself. NaN and missing markers have special comparison behavior. Machine representation can also prevent a decimal calculation from exactly equaling the decimal number you expected. Later examples inspect actual outputs.
기초Foundations
6. 한 값에서 여러 값으로: 길이와 원소를 읽는다6. From one value to several: length and elements
점심 판매량을 하루씩 따로 이름 붙이면 이름이 너무 많아집니다. Python의 리스트 [2, 4, 6]와 R의 수치 벡터 c(2, 4, 6)는 여러 값을 한 객체로 묶는 기본 예입니다. 여기의 값은 문법을 익히기 위한 가정 자료이며 실제 매출 관측이라고 부르지 않습니다.
길이는 3, 합은 12입니다. 길이는 묶음 안의 원소 수이고, 합은 값들을 더한 결과입니다. 여러 값이 같은 수라고 길이가 줄어들지는 않습니다. 나중에 실제 자료에서 같은 값이나 같은 코드가 반복되어도 원행을 먼저 보존해야 하는 이유와 연결됩니다.
Python 리스트와 R 원자 벡터를 같은 이름의 구조라고 생각하지 마세요. 리스트는 서로 다른 자료형의 원소를 담을 수 있고, R 원자 벡터는 원소가 공통 자료형으로 변환될 수 있습니다. R의 list는 또 다른 구조입니다. 다음 묶음에서 이 차이를 실제 출력으로 확인합니다.
Giving every day’s sales a separate variable quickly becomes cumbersome. A Python list [2, 4, 6] and an R numeric vector c(2, 4, 6) are basic ways to collect values. These are toy values for learning syntax, not newly observed sales.
The length is three and the sum is twelve. Length counts elements; summation combines their values. Repeated equal values do not reduce the length. This connects to preserving original rows when actual records repeat a value or code.
A Python list and an R atomic vector are not identical structures. A list can retain differently typed elements; an R atomic vector can coerce elements to a common type. R’s list is another structure. The next group inspects these differences through actual output.
기초Foundations
7. 코드의 위아래 순서는 결과의 일부다7. Instruction order is part of the result
재료를 넣기 전에 완성된 요리를 꺼낼 수 없듯, 아직 만들지 않은 이름을 읽을 수 없습니다. 함수도 먼저 정의한 다음 호출해야 하는 경우를 생각해 봅시다. 다음 코드는 “값 세 개의 합을 길이로 나눈 값을 돌려주는 조리법”을 average라는 이름으로 정의합니다. 함수의 자세한 문법은 D 묶음에서 다시 천천히 배웁니다.
answer는 4인데 마지막 rows의 평균은 15입니다. 답을 계산한 뒤 입력 이름을 다른 값으로 바꾸었기 때문입니다. 과거 답이 현재 입력에 맞게 자동 갱신되지 않았습니다. 오류 메시지가 없어도 결과가 오래된 입력에 근거할 수 있습니다.
현재 rows에 맞는 답이 필요하면 마지막에 answer = average(rows) 또는 answer <- average(rows)를 다시 실행합니다. 분석 보고서에 붙인 숫자가 어느 입력과 코드에서 나왔는지 기록하는 일은 바로 이 작은 문제의 확장입니다.
You cannot retrieve a finished dish before adding its ingredients, or read a name before it exists. Consider a function that must be defined before a call. The following code names a recipe average: divide a collection’s sum by its length. Group D returns to function syntax step by step.
answer is four, while the final rows have mean fifteen. The input name was rebound after calculating the answer. The old answer did not update automatically. A result can depend on stale input without producing an error message.
To answer for the current rows, run the calculation again. Recording which inputs and code produced a reported number is an extension of this small example.
기초Foundations
8. 실습 A: 네 셀의 순서를 바꾸며 기억을 추적한다8. Lab A: trace state while changing the order of four cells
먼저 예상하세요. 1번 셀은 rows에 2,4,6을 할당하고, 2번은 평균 함수를 정의하며, 3번은 answer를 계산하고, 4번은 rows를 10,20으로 바꿉니다. 1→2→3→4와 1→2→4→3의 마지막 답은 같을까요? 3번부터 시작하면 어떤 이름이 없을까요?
네 셀을 한 번씩 실행하는 24개 순서를 두 언어의 새 프로세스에서 실제로 기록했습니다. 단계 0은 아무 셀도 실행하지 않은 상태입니다. 한 단계씩 앞으로 가며 현재 이름·자료형·값·출력·오류를 확인하세요. 이 추적기는 오류를 기록한 뒤 다음 셀로 진행하도록 만들었습니다. 일반 스크립트에서 처리하지 않은 오류가 나도 항상 계속 실행된다는 뜻은 아닙니다.
화면은 준비된 실행 기록을 읽으며 임의 코드를 실행하지 않습니다. “오래된 답” 표시는 이 네 셀에서 답이 사용한 입력과 현재 입력의 기록을 비교한 안내입니다. 모든 프로그램의 숨은 의존성을 자동으로 찾아 주는 도구라고 일반화하지 않습니다. 다른 코드를 시험하려면 실제 Python 또는 R 파일을 수정하고 새 프로세스에서 실행하세요.
Predict first. Cell 1 binds rows to 2, 4 and 6; cell 2 defines the mean function; cell 3 computes the answer; cell 4 rebinds rows to 10 and 20. Do orders 1→2→3→4 and 1→2→4→3 end with the same answer? Which name is absent if cell 3 runs first?
All twenty-four orders were recorded in fresh processes for both languages. Step zero precedes every cell. Advance one step to inspect actual names, types, values, output and errors. This recorder catches an error and continues to the next specified cell; an ordinary script does not necessarily continue after an unhandled error.
The browser reads a prepared execution record and runs no arbitrary code. Its stale-answer annotation compares the recorded input used by cell 3 with the current input in these four cells. It is not a general dependency detector for arbitrary programs. To test different code, edit and run a real Python or R file in a fresh process.
기초Foundations
9. 자료형은 값에 허용되는 연산의 규칙이다9. A type helps determine which operations a value supports
책장 번호 “03”과 책 세 권은 용도가 다릅니다. 번호에서 앞자리 0을 없애면 식별자가 바뀔 수 있지만, 책의 개수에는 3을 수로 써도 됩니다. 보이는 숫자 모양만 보고 모든 열을 수치로 바꾸지 않습니다. 실제 점포 코드나 원행 키는 계산 평균보다 식별·대조에 쓰는 값입니다.
Python의 type(x).__name__, R의 typeof(x)로 내부 자료형을 확인할 수 있습니다. “3”을 두 번 이어 붙이면 “33”이고, 수 3을 두 번 더하면 6입니다. 문자열과 수치의 차이를 출력으로 확인한 뒤 실제 자료 사전에서 그 열의 의미도 읽어야 합니다.
Python
x = 3
y = "3"
print(type(x).__name__, type(y).__name__)
print(x + 2)
print(y + "2")
R
x <- 3
y <- "3"
print(typeof(x)); print(typeof(y))
print(x + 2)
print(paste0(y, "2"))
자료형 검사는 의미 검사를 대신하지 않습니다. 숫자로 보관된 407이 연속적인 고용량을 뜻하지는 않습니다. 수로 변환할 수 있는 것과 평균을 내는 것이 의미 있는 것은 다른 조건입니다.
The identifier “03” and a count of three books serve different purposes. Removing an identifier’s leading zero may change it; a count can be numeric. Do not convert every digit-looking column to a number. Actual store codes and source-row keys support identification and checking rather than meaningful averaging.
Inspect internal types with Python’s type(x).__name__ or R’s typeof(x). Concatenating text “3” twice gives “33”; adding numeric three twice gives six. Inspect behavior and then read the field’s data-dictionary meaning.
Python
x = 3
y = "3"
print(type(x).__name__, type(y).__name__)
print(x + 2)
print(y + "2")
R
x <- 3
y <- "3"
print(typeof(x)); print(typeof(y))
print(x + 2)
print(paste0(y, "2"))
A type check does not replace a meaning check. A numerically stored code 407 is not a continuous employment amount. Being convertible to a number differs from having a meaningful arithmetic average.
기초Foundations
10. 정수·실수와 나눗셈의 결과를 확인한다10. Inspect integer, floating-point and division results
Python에서 3은 정수이고 3.0은 부동소수점 값입니다. R에서 보통 3은 double이고 정수 리터럴은 3L로 표시합니다. 같은 숫자 3을 나타내더라도 내부 종류가 같다고 가정하지 않습니다.
Python
a = 3
b = 3.0
print(type(a).__name__, type(b).__name__)
print(7 / 2, 7 // 2)
R
a <- 3L
b <- 3
print(typeof(a)); print(typeof(b))
print(c(7 / 2, 7 %/% 2))
일반 나눗셈은 3.5를 계산합니다. 바닥 나눗셈은 몫을 아래 정수 방향으로 내려 3을 줍니다. 음수에서는 “소수 부분을 그냥 지우기”와 다를 수 있습니다. 예를 들어 −7/2의 바닥은 −4입니다. 이 차이를 이해하면 구간 번호나 시간 묶음을 계산할 때 경계 오류를 줄일 수 있습니다.
부동소수점은 모든 실수를 정확히 담는 상자가 아닙니다. 측정 정밀도, 자료형의 표현 범위, 출력 자릿수는 서로 다른 개념입니다. 소수점 아래 많은 숫자를 출력했다고 원측정이 더 정밀해지지는 않습니다.
In Python, 3 is an integer and 3.0 is floating point. In R, an ordinary literal 3 is a double; 3L specifies an integer. Equal numerical values need not have identical internal types.
Python
a = 3
b = 3.0
print(type(a).__name__, type(b).__name__)
print(7 / 2, 7 // 2)
R
a <- 3L
b <- 3
print(typeof(a)); print(typeof(b))
print(c(7 / 2, 7 %/% 2))
Ordinary division gives 3.5. Floor division moves the quotient downward to an integer, giving three. For negatives it can differ from deleting fractional digits: the floor of −7/2 is −4. This matters when computing bins or time groups.
Floating point cannot represent every real number exactly. Measurement precision, representable range and printed digits are distinct. Printing more decimals does not improve the original measurement.
기초Foundations
11. 문자를 숫자로 바꾸는 일도 가정이 있는 함수다11. Converting text to a number is an explicit operation
파일에서 읽은 “3.5”는 처음에는 문자일 수 있습니다. Python의 float, R의 as.numeric으로 수치 변환을 요청할 수 있습니다. 원문 “3.5”와 변환한 수치 3.5를 구별해 두면, 원자료를 어떻게 읽었는지 설명하기 쉽습니다.
Python
text = "3.5"
value = float(text)
print(value + 1)
R
text <- "3.5"
value <- as.numeric(text)
print(value + 1)
반대로 “three”를 바꾸면 이 장의 Python 실행은 ValueError를 기록합니다. R 실행은 경고와 함께 NA를 만듭니다. 오류나 경고가 다르게 보인다는 이유로 어느 쪽도 원문에 실제 수치가 있었다고 해석하면 안 됩니다. 변환 실패를 미관측과 같은 표식으로 표시할 경우, 왜 표식이 생겼는지도 기록해야 합니다.
식별자 “03”을 변환하면 수 3이 되어 앞자리 0을 잃을 수 있습니다. 변환 전에 열의 의미를 읽고, 변환 후 실패 개수와 예상 범위를 확인하세요. 원문을 지운 채 실패한 값만 고치면 재검토가 어려워집니다.
A file’s “3.5” can initially be text. Python’s float and R’s as.numeric request numeric conversion. Keeping the source text separate from the resulting number makes the reading rule visible.
Python
text = "3.5"
value = float(text)
print(value + 1)
R
text <- "3.5"
value <- as.numeric(text)
print(value + 1)
Converting “three” records a Python ValueError here. R produces a warning and NA. Neither result establishes that the original text contained an observed number. If conversion failures share a missing marker, retain the reason why the marker appeared.
Converting the identifier “03” to three can lose its leading zero. Read the field meaning first, then check conversion failures and expected ranges. Replacing failures while discarding the original text makes an audit harder.
기초Foundations
12. 논리값은 데이터 선택의 질문에 답한다12. Logical values answer record-selection questions
“값이 25 이상인가?”는 예·아니오로 답하는 질문입니다. 여러 값에 같은 질문을 적용하면 원소별 논리 결과가 생깁니다. 사람 눈으로 고른 행 목록과 코드로 고른 행 목록이 일치하는지 네 값 10,20,30,40부터 확인하세요.
Python
values = [10, 20, 30, 40]
mask = [x >= 25 for x in values]
selected = [x for x in values if x >= 25]
print(mask, selected)
앞 두 값은 거짓, 뒤 두 값은 참이며 선택 결과는 30,40입니다. “행을 고르기 위한 논리 벡터”와 “골라낸 수치값”을 같은 것으로 읽지 않습니다. 마스크의 길이와 원자료 길이를 확인해야 엉뚱한 행을 고르는 실수를 줄일 수 있습니다.
미관측 값이 조건에 들어가면 결과가 단순한 참·거짓만은 아닐 수 있습니다. R의 NA >= 25는 아직 판단할 수 없음을 나타냅니다. 실제 자료에서는 먼저 유효성 규칙을 정하고 선택 조건을 적용합니다. 결측이 포함된 조건을 무조건 거짓으로 간주했다고 조용히 가정하지 않습니다.
“Is this value at least 25?” asks a yes/no question. Applying it to a collection produces elementwise logical results. Start with 10, 20, 30 and 40 to check that a hand-selected list matches the coded selection.
Python
values = [10, 20, 30, 40]
mask = [x >= 25 for x in values]
selected = [x for x in values if x >= 25]
print(mask, selected)
The first two results are false; the last two are true. Selected values are 30 and 40. A logical mask differs from the numeric values selected with it. Check that the mask and source data have matching lengths.
Missing inputs need not produce an ordinary true/false answer. R’s NA >= 25 indicates an unavailable comparison. Define validity before applying a selection condition, and do not silently assume every missing comparison was treated as false.
기초Foundations
13. Python 리스트와 R 벡터는 다르게 연산한다13. Python lists and R vectors do not share every operation
Python의 [1, 2, 3] * 2는 기본 리스트를 두 번 반복합니다. 결과는 1,2,3,1,2,3입니다. 원소를 각각 두 배로 하려면 이 장에서는 [x * 2 for x in values]로 각 원소의 계산을 분명히 씁니다. NumPy 배열은 별도 라이브러리의 구조이며 기본 리스트와 혼동하지 않습니다.
Python
values = [1, 2, 3]
print(values * 2)
print([x * 2 for x in values])
R
values <- c(1, 2, 3)
print(values * 2)
R의 수치 벡터에 2를 곱하면 원소별로 2,4,6이 됩니다. 겉보기 코드가 비슷하다고 같은 연산이라고 가정할 수 없습니다. 결과의 길이와 처음 몇 원소를 확인하면 리스트 반복을 단위 변환으로 오해하는 문제를 쉽게 발견합니다.
R의 c(1, "2", TRUE)는 공통 character 벡터로 변환될 수 있습니다. 각 원소의 종류를 보존하려면 list(1, "2", TRUE)를 쓸 수 있습니다. 이 변환이 원자료의 뜻을 자동으로 정해 주지는 않습니다. 문자열이 되었다고 실제 수치 측정이 사라진 것도, 문자 코드를 수로 바꾸었다고 연속량이 된 것도 아닙니다.
Python’s [1, 2, 3] * 2 repeats a basic list twice, producing six elements. To double each element, this chapter explicitly maps multiplication with [x * 2 for x in values]. A NumPy array belongs to a separate library and is not the basic list.
Python
values = [1, 2, 3]
print(values * 2)
print([x * 2 for x in values])
R
values <- c(1, 2, 3)
print(values * 2)
Multiplying an R numeric vector by two gives elementwise values 2, 4 and 6. Similar-looking syntax need not mean the same operation. Inspecting length and initial elements catches a repeated list mistakenly described as a unit conversion.
R can coerce c(1, "2", TRUE) to a common character vector. list(1, "2", TRUE) retains separately typed components. Coercion does not determine the original meaning: a numeric measurement displayed as text and a numerically encoded category remain different concepts.
기초Foundations
14. 빈 객체는 숫자 0도 미관측 원소 하나도 아니다14. An empty object is neither numeric zero nor one missing element
빈 장바구니, 가격 0인 물건 하나, 가격을 아직 모르는 물건 하나는 다릅니다. 코드에서도 길이 0인 객체와 원소 값 0, 미관측 원소 하나를 나누어 생각합니다. 이 차이는 평균 분모와 함수의 반환 규칙에 직접 영향을 줍니다.
길이는 각각 0,1,1입니다. 빈 합을 0으로 정하는 계산 규약이 있어도, 빈 자료의 평균을 관측값 0이라고 부를 수는 없습니다. 평균은 합을 유효한 원소 수로 나누므로 분모가 0인 경우를 먼저 처리해야 합니다.
실제 Card 자료의 미관측 603행을 삭제해 원행이 애초에 없었던 것처럼 만들지 않습니다. 원기록 길이 3,613과 평균에 들어간 값 3,010을 함께 기록합니다. 빈 객체·결측 표식·결측을 제거한 가용 묶음은 각각 다른 정보입니다.
An empty basket, one free item and one item with unknown price are different. So are an object of length zero, an element equal to zero and one missing element. This affects mean denominators and function-return rules.
The lengths are zero, one and one. A convention assigning zero to an empty sum does not make an empty mean an observed zero. A mean divides by a valid count, so handle count zero first.
Do not erase the 603 unavailable Card rows as though they never existed. Retain both the original 3,613 records and the 3,010 values entering an available-value mean. Empty objects, missing markers and available subsets carry different information.
기초Foundations
15. 출력 자릿수와 정확한 값은 같은 말이 아니다15. Displayed digits do not establish exact arithmetic
십진수 0.1과 0.2를 손으로 더하면 0.3입니다. 그러나 이진 부동소수점에 각각 저장한 뒤 더한 값이, 따로 저장한 0.3과 완전히 같은 비트가 될 필요는 없습니다. 작은 계산 오차가 모든 분석을 무의미하게 만든다는 뜻은 아닙니다. 어떤 비교를 어떤 정밀도로 하려는지 밝혀야 한다는 뜻입니다.
Python
value = 0.1 + 0.2
print(repr(value))
print(value == 0.3)
R
value <- 0.1 + 0.2
print(sprintf("%.17g", value))
print(value == 0.3)
이 장의 두 실제 실행은 긴 표시값과 거짓인 같음 비교를 기록합니다. 화면에서 짧게 0.3으로 보이도록 반올림해도 저장된 값이 새로 정확해지는 것은 아닙니다. 반대로 “거의 같다”는 비교를 쓸 때도 허용오차를 문제의 단위·규모와 연결해야 합니다. 근거 없이 모든 곳에 같은 작은 상수를 더하지 않습니다.
인덱스나 원행 키처럼 정수로 정확하게 다룰 수 있는 정보는 소수 근삿값으로 바꾸지 않습니다. 수리기초의 반올림오차 장에서 다룬 계산 오차와, 조사에서 원래 얻지 못한 결측값도 구별하세요. 한쪽을 고친다고 다른 쪽이 해결되지는 않습니다.
Decimal arithmetic gives 0.1 + 0.2 = 0.3. Binary floating-point addition of separately stored approximations need not equal the independently stored approximation to 0.3 bit for bit. This does not make every analysis meaningless; it requires explaining the precision and comparison relevant to a task.
Python
value = 0.1 + 0.2
print(repr(value))
print(value == 0.3)
R
value <- 0.1 + 0.2
print(sprintf("%.17g", value))
print(value == 0.3)
Both archived runs record the long display and a false equality result. Rounding the screen to 0.3 does not change the stored value into an exact decimal. A “close enough” comparison likewise needs a tolerance justified by units and scale, not an unexplained constant added everywhere.
Keep exactly representable integer indices and source-row keys separate from approximate quantities. Numerical error differs from an observation never collected. Fixing one does not automatically resolve the other.
기초Foundations
16. 실습 B: 자료형을 먼저 예상하고 실제 기록을 확인한다16. Lab B: predict types before revealing actual recorded output
먼저 숫자와 문자, 정수와 실수, 혼합 묶음, 변환 실패, 리스트 반복, 빈 자료, 소수 덧셈 중 하나를 고르세요. 실행 전 코드가 출력할 값과 자료형을 한 줄로 적습니다. 그 뒤 실제 Python 또는 R 실행 기록을 열어 예상과 비교합니다.
같은 질문을 두 언어로 바꾸어 확인할 때에는 문법만 번역하지 말고 객체 종류도 읽으세요. Python 리스트의 곱셈과 R 수치 벡터의 곱셈, 잘못된 수치 변환의 오류와 경고를 특히 비교합니다. 보관된 코드 해시와 버전은 어떤 실행을 보고 있는지 식별합니다. 해시 일치만으로 코드의 의미가 옳다고 증명되는 것은 아닙니다.
확인 질문: 현재 코드가 쓰는 값의 자료형이 적절한가요? 바뀐 값은 원문을 보존하고 있나요? 화면 출력과 반환값을 혼동하지 않았나요? 앞으로의 실습에서도 결과 숫자 하나보다 이 질문을 먼저 적용하세요.
Choose numbers versus text, integer versus floating point, mixed containers, failed conversion, list repetition, empty objects or decimal addition. Before revealing output, write a prediction of the value and type. Then compare it with the actual archived Python or R run.
When switching languages, inspect the object as well as the syntax. Compare Python list multiplication with R numeric-vector multiplication, and an invalid conversion’s error with its warning. A code hash and runtime version identify the recorded execution; matching hashes alone do not prove that its analysis is meaningful.
Ask whether the type fits the field, whether transformations retain the source and whether displayed output has been mistaken for a returned value. Apply these checks before focusing on one final number.
기초Foundations
17. 첫째 위치가 0인지 1인지 먼저 확인한다17. Check whether the first position is zero or one
사물함을 왼쪽에서 세면 첫째·둘째·셋째라는 순서가 있습니다. 코드의 인덱스는 그 위치를 부르는 번호입니다. Python의 기본 리스트는 첫 원소를 0으로 부르고, R의 기본 벡터는 보통 첫 원소를 1로 고릅니다. 숫자 0이 첫 관측값이라는 뜻이 아니라 위치를 부르는 약속입니다.
두 코드 모두 첫 값 10과 마지막 값 40을 출력합니다. 위치와 원소 값을 나누어 적으면 혼동이 줄어듭니다. 길이 4인 Python 리스트의 유효한 비음수 위치는 0,1,2,3이며, R 벡터의 네 원소는 1,2,3,4로 고릅니다.
원자료의 sourceRow=42와 현재 객체의 42번째 위치도 같지 않을 수 있습니다. 정렬하거나 일부 행을 선택하면 현재 위치가 바뀌기 때문입니다. 원행 키는 별도 필드로 보존해야 나중에 원문과 대조할 수 있습니다.
Lockers have first, second and third positions. An index is a convention for naming a position. A basic Python list starts at index zero; an R vector ordinarily selects its first element with one. This does not make zero the first observed value.
Both examples print the first value ten and last value forty. Separate positions from values. Four Python elements have nonnegative indices zero through three; four R elements use one through four.
An original sourceRow=42 is not necessarily the current collection’s forty-second position. Sorting or selecting changes positions. Preserve the source-row key as its own field for later checks.
기초Foundations
18. 구간 선택은 시작·끝·포함 규칙을 함께 읽는다18. Read a slice with its start, end and inclusion rule
Python의 values[0:2]는 위치 0에서 시작하여 위치 2 바로 앞에서 끝납니다. 따라서 앞 두 원소 10,20을 고릅니다. R의 values[1:2]는 1과 2라는 인덱스를 만들어 두 위치를 고릅니다. 같은 앞 두 값을 얻지만 끝점을 읽는 방법이 다릅니다.
같은 숫자 두 개를 쓴 Python 구간 2:2는 빈 리스트를 줍니다. 반면 R의 2:2는 인덱스 2 하나이므로 두 번째 값 20을 줍니다. 코드의 콜론 모양만 보고 두 언어에 같은 구간 관례를 적용하지 않습니다.
끝점을 포함하는지 손으로 위치표를 그린 뒤 선택된 개수를 확인하세요. 시간 자료에서 “첫 9개월”과 “9번 위치까지”를 혼동하거나, 학습 구간의 마지막 행이 시험 구간에도 들어가면 실제 분석의 질문이 바뀔 수 있습니다.
Python’s values[0:2] starts at zero and stops before two, selecting ten and twenty. R’s values[1:2] constructs indices one and two. The outputs match, but the boundary conventions differ.
A Python slice with equal start and stop, 2:2, is empty. In R, 2:2 is the single index two and selects twenty. A colon’s appearance does not establish shared semantics across languages.
Draw a position table and count selected elements before processing a large file. Confusing the first nine months with a position boundary, or including a training endpoint in a test set, can change an actual analysis.
기초Foundations
19. 음수 인덱스는 뒤에서 세기와 제외하기가 다르다19. A negative index can mean counting backward or excluding
Python 기본 리스트에서 values[-1]은 마지막 원소입니다. 뒤에서 첫째라는 약속입니다. R 기본 벡터에서 values[-1]은 첫 번째 원소를 제외한 나머지입니다. 같은 글자 모양에 서로 다른 질문이 들어 있습니다.
Python 첫 출력은 40이고, R 첫 출력은 20,30,40입니다. R에서 마지막 원소를 고르려면 여기서는 길이를 계산해 그 위치를 선택합니다. 입력을 자르려는지 원소 하나를 읽으려는지 목표부터 말해 보세요.
잘못된 음수 인덱스가 언제나 즉시 오류를 주는 것은 아닙니다. R에서 첫 행만 빠진 수치 벡터도 계산은 계속될 수 있습니다. 결과가 출력되었다는 사실만으로 원래 의도한 행을 골랐다고 확신하지 말고, 길이·원행 키·처음과 마지막 값을 확인합니다.
For a basic Python list, values[-1] reads the final element. For an R vector, values[-1] excludes the first element. Identical-looking code asks different questions.
Python prints forty. R’s first result contains twenty, thirty and forty. To read the final R element here, use its length as the position. State whether you intend to remove an element or retrieve one.
An unintended selection need not immediately raise an error. R can continue calculating with the first row excluded. Printed output alone does not establish that the intended rows were used. Check length, source keys and endpoint values.
기초Foundations
20. 범위 밖 값과 원래 미관측 값을 구별한다20. Distinguish an out-of-range result from original missing data
길이 4인 Python 리스트에서 values[4]를 읽으면 이 실행은 IndexError를 냅니다. 길이 4인 R 원자 벡터의 values[5]는 NA를 돌려줍니다. 여기의 R 표식은 원조사에서 관측하지 못한 다섯째 값이 아니라, 존재하지 않는 위치를 요청해 생긴 계산 결과입니다.
R의 values[0]은 첫 값이 아니라 길이 0인 같은 기본 종류의 결과입니다. “0번째 관측값”과 “관측값 0”을 혼동하지 않습니다. 이 절의 규칙은 기본 리스트·원자 벡터에 대한 것이며, 다른 자료 구조나 라이브러리는 별도 규칙을 가질 수 있습니다.
오류를 고칠 때는 메시지를 먼저 읽고 예상한 길이와 실제 길이를 비교합니다. 무조건 마지막 행을 복사해 범위를 채우거나, 만들어진 NA를 0으로 바꾸면 선택 오류를 데이터 조작으로 숨길 수 있습니다.
Reading values[4] from a four-element Python list records IndexError. Reading values[5] from a four-element R atomic vector returns NA. That marker arose from requesting a nonexistent position; it is not a fifth original survey observation with an unavailable measurement.
R’s index zero returns a length-zero object rather than the first value. An index zero differs from an observation equal to zero. These statements concern the basic structures used here; other structures and libraries can define different rules.
Read the message and compare expected with actual length. Copying a final row to fill the gap, or zero-filling a newly created NA, can conceal a selection error through data alteration.
기초Foundations
21. 조건 선택에서도 위치와 원행 키를 함께 보존한다21. Preserve source keys when filtering by a condition
값을 따로 정렬한 뒤 예전 행 이름을 옆에 붙이면 짝이 틀어질 수 있습니다. 아직 큰 표를 다루기 전이라도, 각 관측을 이름 있는 작은 기록으로 묶는 습관을 배워 둡시다. 아래 세 값과 원행 키는 문법을 위한 가정 자료입니다.
Python
records = [{"source_row": 11, "value": 2},
{"source_row": 25, "value": 8},
{"source_row": 42, "value": 4}]
selected = [row for row in records if row["value"] >= 4]
print([(row["source_row"], row["value"]) for row in selected])
R
source_row <- c(11, 25, 42)
value <- c(2, 8, 4)
keep <- value >= 4
print(source_row[keep]); print(value[keep])
선택한 원행 키는 25,42이고 값은 8,4입니다. 코드가 모두 맞아도 키와 값을 서로 다른 순서로 따로 바꾸면 잘못된 관측 쌍을 만들 수 있습니다. 표 결합과 키 검증은 뒤 장에서 더 자세히 다루며, 여기서는 동일한 조건을 같은 위치에 적용하는 원리를 익힙니다.
Sorting values separately and reattaching old labels can break record pairing. Before working with large tables, learn to keep each observation’s fields together. The following source keys and values are explicitly toy data.
Python
records = [{"source_row": 11, "value": 2},
{"source_row": 25, "value": 8},
{"source_row": 42, "value": 4}]
selected = [row for row in records if row["value"] >= 4]
print([(row["source_row"], row["value"]) for row in selected])
R
source_row <- c(11, 25, 42)
value <- c(2, 8, 4)
keep <- value >= 4
print(source_row[keep]); print(value[keep])
Selected source keys are 25 and 42, paired with eight and four. Correct syntax cannot rescue labels and values independently reordered into false pairs. Later chapters develop joins and key checks; here apply the same selection to corresponding positions.
기초Foundations
22. 반복은 매 단계의 이름과 누적값을 추적한다22. Trace each element and accumulated value in a loop
반복문은 같은 작업을 여러 원소에 적용하는 방법입니다. 가정 자료 2,4,6의 합을 구할 때 누적값을 처음 0으로 만들고, 원소를 하나씩 더해 봅시다. 반복 변수 value는 매번 다음 원소를 가리키고, total은 앞에서 계산한 누적값에 새 원소를 더합니다.
Python
values = [2, 4, 6]
total = 0
for value in values:
total = total + value
print(value, total)
R
values <- c(2, 4, 6)
total <- 0
for (value in values) {
total <- total + value
print(c(value, total))
}
각 단계의 (원소,누적합)은 (2,2),(4,6),(6,12)입니다. 마지막 누적합만 보면 원소를 빠뜨렸는지 알기 어려울 수 있습니다. 작은 자료에서 단계별 값을 먼저 확인하고, 긴 실제 자료에서는 필요한 검사만 남기는 방식으로 옮겨갑니다.
R에서 길이가 0일 수 있는 객체를 위치로 반복하려면 seq_along(values)가 의도를 잘 드러냅니다. 1:length(values)는 길이 0에서 1:0, 즉 1과 0을 만들어 빈 반복이 되지 않습니다. Python의 range(len(values))는 길이 0에서 빈 범위를 만듭니다.
A loop applies an operation to several elements. To sum toy values 2, 4 and 6, initialize an accumulator to zero and add each element. value names the next element; total combines the previous accumulator with it.
Python
values = [2, 4, 6]
total = 0
for value in values:
total = total + value
print(value, total)
R
values <- c(2, 4, 6)
total <- 0
for (value in values) {
total <- total + value
print(c(value, total))
}
The (element, accumulated sum) pairs are (2, 2), (4, 6) and (6, 12). One final sum can conceal a skipped element. Inspect a small example step by step before keeping appropriate checks in a larger calculation.
For positional iteration over possibly empty R objects, seq_along(values) expresses the intended sequence. 1:length(values) instead becomes 1:0 at length zero, producing one and zero. Python’s range(len(values)) is empty at length zero.
기초Foundations
23. 이름 있는 기록으로 실제 원행을 읽는다23. Read an actual source row through named fields
다음은 실제 Card–Krueger 원행 42의 일부 값을 설명하기 위해 작은 기록으로 적은 예입니다. 점포 코드는 407이고, 전 시점 FTE는 11입니다. 이 코드를 현재 배열의 407번째 위치라고 읽지 않습니다. FTE는 전일제 상당 고용량이며 단순한 사람 머릿수와 구별합니다.
Python
record = {"source_row": 42, "store_code": "407", "before_fte": 11.0}
print(record["source_row"], record["before_fte"])
R
record <- list(source_row=42, store_code="407", before_fte=11)
print(record$source_row); print(record$before_fte)
이 작은 기록은 전체 원파일을 다시 읽은 것과 같지는 않습니다. 실제 파일에서 같은 코드 407인 원행 168은 다른 주·체인과 12→14.5의 FTE를 가집니다. 코드가 같다는 이유만으로 둘을 지우거나 합치지 말고 원행 키를 보존합니다. 뒤 실제 자료 실습에서는 두 원행을 파일에서 다시 찾아 비교합니다.
The next small record illustrates selected actual fields from Card–Krueger source row 42: store code 407 and before-wave FTE eleven. The code is not position 407 in the current collection. Full-time-equivalent employment differs from an unweighted head count.
Python
record = {"source_row": 42, "store_code": "407", "before_fte": 11.0}
print(record["source_row"], record["before_fte"])
R
record <- list(source_row=42, store_code="407", before_fte=11)
print(record$source_row); print(record$before_fte)
Writing this small record is not the same as rereading the entire original file. Source row 168 has the same code 407 but another state/chain and FTE twelve→fourteen and a half. Equal codes do not justify deletion or aggregation. Preserve source keys; the actual-data lab retrieves both records from the file.
기초Foundations
24. 실습 C: 하나의 선택을 손으로 먼저 그린다24. Lab C: draw a selection by hand first
먼저 10,20,30,40의 네 칸과 각 언어의 위치를 적으세요. 첫 값·마지막 값·음수 위치·구간·범위 밖·0 위치·조건·빈 반복·이름 있는 기록 중 하나를 고르고, 선택 결과의 값과 길이를 예상합니다. 그 뒤 실제 실행 기록을 확인합니다.
특히 같은 [-1]과 [2:2]가 다른 질문이라는 점을 설명해 보세요. 오류가 나온 경우는 이름·위치·객체 종류 중 무엇이 원인인지 구분합니다. R에서 NA가 나왔다면 원자료의 미관측인지 범위 밖 요청이 만든 것인지도 확인하세요.
이 실습은 고정 코드와 가정 네 값의 실행을 추적합니다. 실제 자료를 새로 뽑거나 선택한 행이 대표 표본임을 증명하지 않습니다. 실제 분석에 적용할 때에는 원행 키와 관측 단위의 대조를 함께 해야 합니다.
Draw four cells containing 10, 20, 30 and 40 and annotate each language’s positions. Choose first, last, negative index, slice, out-of-range, zero index, mask, empty iteration or a named record. Predict values and length before inspecting actual recorded execution.
Explain why identical [-1] or [2:2] syntax can ask different questions. Diagnose whether an error concerns a name, position or object type. An R NA may have arisen from an out-of-range request rather than original missing data.
The lab traces fixed snippets and toy values. It does not collect new data or establish that selected rows form a representative sample. Actual applications additionally require source-key and observation-unit checks.
기초Foundations
25. 함수는 입력을 받아 반환값을 만드는 작은 약속이다25. A function connects explicit inputs to a returned result
앞 절에서 여러 번 쓴 평균을 함수로 묶어 봅시다. 가정 자료 2,4,6을 받으면 합 12와 길이 3으로 평균 4를 계산합니다. 같은 조리법에 10,20을 주면 15가 나옵니다. 함수 정의를 적는 순간 이 모든 입력의 계산을 미리 수행하는 것은 아닙니다. 호출할 때 전달한 입력으로 본문이 실행됩니다.
Python은 들여쓰기로 함수 본문을 구분합니다. R 예제는 중괄호 안을 본문으로 묶습니다. values는 이 함수가 입력에 붙이는 이름이고, return은 호출한 곳으로 결과를 돌려줍니다. 입력은 이 예제에서 비어 있지 않은 수치 묶음이라는 전제가 있습니다. 결측·빈 묶음 처리는 뒤에서 추가합니다.
Package the repeated mean calculation as a function. Toy input 2, 4, 6 has sum twelve and length three, giving four; input 10, 20 gives fifteen. Defining the recipe does not precompute every possible input. Calling it executes the body with the supplied values.
Python indentation identifies the body; this R example uses braces. values names the supplied input locally, and return sends a result to the caller. The example assumes a nonempty numeric collection. Missing and empty inputs require additional policy developed below.
기초Foundations
26. 인자 이름과 실제로 전달한 값을 나눈다26. Distinguish a parameter name from its supplied argument
함수의 입력 이름이 values라고 해서 바깥 자료도 꼭 같은 이름이어야 하는 것은 아닙니다. 바깥의 lunch_sales 값을 전달하면 함수 안에서 그 입력을 values라는 이름으로 읽습니다. 숫자 하나를 돌려주면 바깥에서는 answer 같은 다른 이름에 저장할 수 있습니다.
설명을 연습할 때 화살표를 세 개 그려 보세요. 바깥 입력 묶음 → 함수의 입력 이름 → 반환된 평균입니다. 파일 전체나 과거 변수에 조용히 의존하는 함수보다, 필요한 입력을 인자로 분명하게 받는 함수가 작은 예제에서 검증하기 쉽습니다.
인자 전달의 모든 복사·평가 규칙이 두 언어에서 같다는 뜻은 아닙니다. 특히 R의 평가 방식이나 Python 변경 가능한 객체는 더 세밀한 규칙이 있습니다. 이 절에서는 값을 명시적으로 전달하고, 필요한 결과를 반환하며, 실제 실행으로 확인하는 범위에 집중합니다.
A parameter named values does not require the caller’s object to have that name. Pass lunch_sales; inside the call, the function refers to the supplied collection as values. Store the returned number under another name such as answer.
Draw three arrows: caller’s input collection → local parameter name → returned mean. Explicitly supplied inputs make a small function easier to test than hidden dependence on an entire file or old variables.
This is not a claim that both languages share every copying or evaluation rule. R evaluation and Python mutable objects have additional details. Here make inputs and returns explicit and check actual execution.
기초Foundations
27. 화면에 보인 답과 호출자에게 돌아온 값은 다를 수 있다27. Displayed output can differ from a returned value
친구에게 답을 말하는 일과 답을 적은 쪽지를 건네주는 일을 구별해 봅시다. 함수가 화면에 숫자 4를 출력해도 그 함수를 호출한 곳이 숫자 4를 반환값으로 받았다는 보장은 없습니다. Python의 다음 함수는 print만 하고 명시적 반환이 없어 None을 돌려줍니다.
R의 이 예제는 마지막 cat의 반환값 NULL이 answer에 저장됩니다. 출력 작업을 하는 모든 R 함수가 NULL을 반환한다는 뜻은 아닙니다. 예를 들어 print는 대상 값을 보이지 않는 방식으로 반환할 수 있으므로, 정확히 어떤 함수를 썼는지 확인해야 합니다.
평균을 다음 계산에 쓰려면 숫자를 return하고 필요할 때 호출자 쪽에서 출력하는 구성이 명확합니다. 숫자·표·그림 중 무엇이 함수의 결과물인지 문서화하면 후속 분석에서 None이나 NULL을 평균값으로 잘못 쓰는 일을 줄일 수 있습니다.
Saying an answer aloud differs from handing someone a written answer. A function can print four without returning numeric four to its caller. The Python function below only prints and therefore returns None.
This R example stores the final cat call’s NULL return. It does not imply that every R printing function returns NULL: print, for example, can return its object invisibly. Inspect the particular function.
For a mean used in later arithmetic, explicitly return the number and let the caller print when needed. Document whether a function produces a number, table or plot so that None or NULL is not mistaken for a computed mean.
기초Foundations
28. 마지막 식을 썼다고 두 언어가 같은 것을 반환하지 않는다28. The final expression has different return behavior
Python에서 함수 본문에 value * 2만 쓰고 return을 생략하면 그 값이 자동으로 반환되지 않습니다. 함수는 암묵적으로 None을 반환합니다. R의 다음 함수는 마지막으로 평가한 식의 값 6을 반환합니다. 이런 차이는 실행이 성공했는데도 후속 답이 미관측처럼 보이는 원인이 됩니다.
Python
def double(value):
value * 2
answer = double(3)
print(answer)
두 언어를 배우는 초기에는 반환하려는 값을 명시적 return으로 적으면 의도를 비교하기 쉽습니다. 그 뒤 실제 코드의 관용구를 읽으며 생략된 규칙을 익혀도 늦지 않습니다. 문장을 줄이는 것보다 입력과 결과의 약속을 이해하는 것이 먼저입니다.
In a Python function, merely evaluating value * 2 does not return that value. Without an explicit return, the function returns None. The R function below returns its last evaluated expression, six. This difference can leave later calculations without the number you expected despite successful execution.
Python
def double(value):
value * 2
answer = double(3)
print(answer)
Initially, explicit return statements help make intent comparable. Later learn idiomatic omitted returns by reading their rules. Understanding the input/result contract comes before shortening code.
기초Foundations
29. 기본값과 이름 있는 인자는 단위 변환을 읽기 쉽게 한다29. Defaults and named arguments clarify a unit conversion
섭씨를 화씨로 바꾸는 식은 값×9/5+32입니다. 일반적인 선형·아핀 변환을 convert(value, scale, shift)로 적어 봅시다. 기본값 scale=1,shift=0은 입력을 그대로 돌려줍니다. 기본값이 있다는 것은 그 선택을 바꾸지 않고 사용해도 된다는 약속이며, 단위 의미를 자동으로 맞춘다는 뜻은 아닙니다.
두 실제 실행에서 20°C는 68°F가 됩니다. 인자 이름을 정확히 쓰면 호출에서 scale과 shift의 순서가 바뀌어도 뜻을 읽기 쉽습니다. 이 장에서는 R의 부분 인자 이름 맞추기 같은 편의 규칙에 기대지 않고 전체 이름을 씁니다.
입력 20이 °C인지 kg인지 함수는 이 숫자만으로 알지 못합니다. kg를 g로 바꾸려면 scale=1000,shift=0이라는 별도 의미를 기록합니다. 이름 있는 인자는 사람이 약속을 읽게 도와주지만 자료의 단위를 검증하는 일을 대신하지 않습니다.
Celsius-to-Fahrenheit conversion multiplies by 9/5 and adds 32. Write a general affine conversion as convert(value, scale, shift). Defaults scale=1 and shift=0 preserve the input. A default is a chosen behavior, not automatic unit validation.
Both archived runs map 20°C to 68°F. Full argument names make the meaning clear even when their call order changes. This chapter uses complete names rather than relying on conveniences such as R partial argument matching.
A bare number twenty does not tell the function whether it means °C or kg. Converting kg to g uses a separately documented scale of one thousand and shift zero. Named arguments aid reading but do not replace measurement-unit checks.
기초Foundations
30. 함수의 입력 범위와 빈 묶음 규칙을 정한다30. Define valid inputs and an empty-input policy
함수 이름이 average라고 해서 모든 객체의 평균을 알아서 구하는 것은 아닙니다. 숫자 묶음인지, 미관측이 있는지, 유효값이 하나라도 있는지에 따라 규칙이 필요합니다. 비어 있는 값의 합을 길이 0으로 나누면 Python은 이 예제에서 ZeroDivisionError를 내고 R은 NaN을 만듭니다.
average <- function(values) {
if (length(values) == 0) return(NA_real_)
sum(values) / length(values)
}
print(average(numeric(0)))
이제 빈 입력에는 명시적으로 None 또는 수치형 NA를 반환합니다. 관측 평균 0이라고 꾸미지 않습니다. 모든 빈 입력을 같은 방식으로 처리해야 한다는 보편 규칙은 아닙니다. 어떤 함수는 오류로 거부할 수도 있습니다. 중요한 것은 계약을 쓰고 그 경계를 실제로 검사하는 것입니다.
kg→g 함수에 문자 “4.2”를 넣었을 때 조용히 추측할지 명시적으로 거부할지도 정해야 합니다. 이 장의 검사 예제는 수치 입력 하나를 요구합니다. Python의 bool은 정수와 관련된 자료형이므로 참·거짓을 질량으로 받지 않으려면 그 경우도 분명히 제외합니다.
A function named average does not know the intended mean of every object. Specify numeric inputs, missingness and a positive valid count. Dividing an empty sum by length zero raises Python ZeroDivisionError here and produces R NaN.
average <- function(values) {
if (length(values) == 0) return(NA_real_)
sum(values) / length(values)
}
print(average(numeric(0)))
This explicit policy returns None or numeric NA, not an invented observed mean zero. Another valid function contract could reject empty inputs with an error. State the chosen contract and test its boundary.
Also decide whether a kg-to-g function should guess the meaning of text “4.2” or reject it. The validation example requires one numeric input. Python bool relates to integer behavior; explicitly exclude it when logical values must not be accepted as masses.
기초Foundations
31. 함수 안의 이름과 밖의 이름을 구별한다31. Separate local bindings from outer bindings
함수의 지역 이름은 호출 중 사용하는 이름입니다. 바깥 x가 100인데 함수의 입력 이름도 x라면, 호출한 입력 3을 함수 안의 x로 읽을 수 있습니다. 다음 숫자 예에서 함수는 입력에 1을 더해 4를 반환하지만 바깥 x는 100으로 남습니다.
Python
x = 100
def plus_one(x):
x = x + 1
return x
answer = plus_one(3)
print(answer, x)
R
x <- 100
plus_one <- function(x) {
x <- x + 1
return(x)
}
answer <- plus_one(3)
print(c(answer, x))
이 예제는 함수 안에서 숫자 인자 이름에 다시 할당한 경우입니다. “어떤 함수도 바깥을 바꿀 수 없다”는 일반 정리가 아닙니다. 전역 할당, 공유 가능한 변경 객체, 파일 쓰기 같은 부수효과는 별도로 존재합니다. 초심자 분석 함수에서는 그런 숨은 변경을 줄이고 입력과 반환을 분명히 하는 편이 검증에 유리합니다.
같은 입력으로 함수를 두 번 호출해 같은 결과를 얻는지 확인하세요. 결과가 과거 호출 횟수나 수정된 외부 변수에 따라 달라지면 그 의존성을 먼저 설명해야 합니다. 새 프로세스 재현은 이런 숨은 상태를 찾아내는 한 방법입니다.
Local names are used during a call. An outer x can equal one hundred while a parameter also named x receives three. In this numeric example, the function returns four but leaves the outer x at one hundred.
Python
x = 100
def plus_one(x):
x = x + 1
return x
answer = plus_one(3)
print(answer, x)
R
x <- 100
plus_one <- function(x) {
x <- x + 1
return(x)
}
answer <- plus_one(3)
print(c(answer, x))
This demonstrates local rebinding of a numeric parameter, not a theorem that no function can alter anything outside itself. Global assignments, mutable shared objects and file writes can cause side effects. Beginner analysis functions are easier to check when inputs and returns are explicit and hidden changes are minimized.
Call a function twice on the same input and inspect its behavior. Dependence on previous calls or external state needs explanation. Fresh-process reproduction helps expose such dependencies.
기초Foundations
32. 실습 D: 입력·지역 이름·출력·반환을 각각 확인한다32. Lab D: inspect inputs, local names, output and return separately
먼저 반환값을 예상하세요. 평균 반환, 출력만 하는 함수, 마지막 식, 지역 이름, 단위 인자, 빈 입력, 입력 검사를 하나씩 고릅니다. 화면에 보인 수와 answer에 저장된 자료형·값을 함께 읽습니다.
함수가 잘못된 입력을 거부했다면 무조건 오류를 없애는 것부터 하지 마세요. 계약에 맞게 거부한 것인지, 정말 올바른 입력을 잘못 거부한 것인지 나누어 봅니다. None·NULL·NA·NaN도 이름이 비슷하다고 서로 교환 가능한 평균값으로 쓰지 않습니다.
마지막 확인: 실제 국가 지표나 로그 임금 묶음을 이 함수에 넣으려면 어떤 입력 변환·결측 규칙·단위 기록을 추가해야 할까요? 다음 묶음에서 미관측을 처리한 뒤 실제 파일에 작은 함수를 적용합니다.
Predict the return first. Select an explicit mean return, display-only function, final expression, local binding, unit argument, empty input or input validation. Read both printed output and the type/value actually bound to answer.
Do not automatically suppress every error. Decide whether the function correctly rejected an invalid input or incorrectly rejected a valid one. None, NULL, NA and NaN are not interchangeable numeric means.
What input conversion, missingness policy and unit documentation are needed before applying this function to actual country indicators or log wages? The next group develops missingness before using small functions on actual files.
기초Foundations
33. 관측값 0과 값을 모른다는 표식은 다르다33. Observed zero differs from a missing-value marker
어느 날 매출이 0이었다는 기록은 그날 아무것도 팔리지 않았다는 관측입니다. 매출을 적지 못했다는 표식은 값이 무엇인지 모른다는 정보입니다. 둘을 같게 바꾸면 평균과 선택 조건의 뜻이 바뀝니다. 가정 값 2,미관측,4,0을 생각해 봅시다.
Python
values = [2, None, 4, 0]
valid = [x for x in values if x is not None]
print(len(values), len(valid), sum(valid) / len(valid))
원소는 4개이고 가용값은 3개입니다. 가용 합은 6,평균은 6/3=2입니다. 0도 실제로 관측된 가용값이므로 분모에 들어갑니다. 미관측을 0으로 채워 6/4=1.5로 바꾸면 다른 자료·다른 규칙을 만든 것입니다.
실제 Card 파일에서는 원로그가 없는 603행을 0으로 바꾸지 않습니다. 로그값 0 자체는 원단위 값 1에 대응하는 수치이며 결측과 다릅니다. “자료 없음”의 표시는 확률적 결측 원인을 설명하지도 않습니다. 표식 처리와 결측에 대한 추론은 서로 다른 층위입니다.
An observed zero in sales means nothing was sold. A missing marker means the amount was not recorded. Replacing the latter with the former changes a mean and its selection rules. Consider toy values two, missing, four and zero.
Python
values = [2, None, 4, 0]
valid = [x for x in values if x is not None]
print(len(values), len(valid), sum(valid) / len(valid))
There are four elements but three available values. Their sum is six and mean two. Observed zero belongs in the denominator. Filling the missing entry with zero instead gives six divided by four, a different dataset and rule.
Preserve the 603 unavailable Card logs. A logged value zero corresponds to one in the original wage units, not missingness. A marker also does not explain why a value is missing. Programming the marker and inferring the missingness mechanism are different tasks.
기초Foundations
34. 결측을 자기 자신과 비교해 찾으려 하지 않는다34. Do not identify every missing marker through self-equality
Python에서 None이라는 표식을 쓴 이 예제는 x is None으로 확인합니다. 수치 계산의 NaN은 math.isnan으로 확인할 수 있습니다. 두 객체는 같은 종류가 아닙니다. math.isnan(None)을 무조건 호출하는 것은 올바른 수치 입력 검사가 아닙니다.
Python
import math
value = float("nan")
print(value == value, math.isnan(value))
print(None is None)
R
value <- NaN
print(value == value)
print(is.na(value)); print(is.nan(value))
print(is.na(NA_real_)); print(is.nan(NA_real_))
Python NaN의 자기 같음 비교는 거짓입니다. R의 NaN 또는 NA를 같음 비교하면 판단 불가를 나타내는 NA가 나올 수 있습니다. R의 is.na는 NA와 NaN을 모두 찾고, is.nan은 이 예제에서 NaN과 일반 NA를 구별합니다.
따라서 x == NA 같은 비교를 “가용값인가”의 조건으로 외우지 않습니다. 어떤 표식·자료형을 받는 함수인지 정한 뒤, 그 종류에 맞는 판정 함수를 씁니다. 비교가 거짓 또는 미정의라는 사실을 관측값 0으로 번역하지 않습니다.
For a Python example using None as its marker, test x is None. Numeric NaN can be tested with math.isnan. These are different objects; unconditionally calling math.isnan(None) is not a valid numeric-input check.
Python
import math
value = float("nan")
print(value == value, math.isnan(value))
print(None is None)
R
value <- NaN
print(value == value)
print(is.na(value)); print(is.nan(value))
print(is.na(NA_real_)); print(is.nan(NA_real_))
Python NaN self-equality is false. R equality involving NaN or NA can return NA, an unavailable comparison. R is.na detects both markers; is.nan distinguishes NaN from ordinary NA here.
Do not use x == NA as a memorized availability test. State accepted types and markers, then use the appropriate test. A false or unavailable comparison is not an observed numeric zero.
기초Foundations
35. None·NULL·NA·NaN의 역할과 길이를 나눈다35. Separate the roles and lengths of None, NULL, NA and NaN
Python의 None은 이 장에서 결과 없음·미관측 표식으로 사용하지만, 언어가 모든 자료 분석의 결측 규칙을 그 하나로 정해 준 것은 아닙니다. Python 리스트 [None]은 길이 1이고 빈 리스트는 길이 0입니다. None 자체를 수치 평균이라고 사용하면 안 됩니다.
Python
a = None
b = [None]
c = []
print(a, len(b), len(c))
R
a <- NULL
b <- NA_real_
c <- numeric(0)
print(c(length(a), length(b), length(c)))
R의 NULL은 여기서 길이 0,수치형 NA 하나는 길이 1입니다. numeric(0)도 길이 0이지만 NULL과 같은 자료형은 아닙니다. NaN은 수치적으로 정의되지 않는 결과에 쓰이는 표식입니다. 이름이 비슷하다는 이유로 서로 바꾸지 말고 자료형·길이·생성 이유를 함께 확인합니다.
“함수가 값을 반환하지 않았다”와 “관측 대상 하나의 값이 미관측이다”도 다릅니다. 앞의 출력 전용 함수가 반환한 None/NULL을 원자료의 결측값 수에 더하지 않습니다. 코드 실행 결과와 실제 기록을 같은 표로 섞지 않는 연습입니다.
Python None is used here for unavailable results or inputs, but it is not a universal missingness policy for all libraries. A list containing None has length one; an empty list has length zero. None is not a numeric mean.
Python
a = None
b = [None]
c = []
print(a, len(b), len(c))
R
a <- NULL
b <- NA_real_
c <- numeric(0)
print(c(length(a), length(b), length(c)))
R NULL has length zero here; one numeric NA has length one. numeric(0) also has length zero but a different type from NULL. NaN represents a numerically undefined result. Inspect type, length and origin rather than interchanging similar-looking names.
A function returning no value differs from one actual observational unit having an unavailable measurement. Do not add a display-only function’s None/NULL return to a source dataset’s missing-record count.
기초Foundations
36. 평균 함수는 표식·가용 분모·유한값 조건을 약속한다36. A mean function needs a marker and denominator contract
평균 함수의 첫 계약을 적어 봅시다. 이 장의 Python 실제 자료 함수는 수치 또는 None을 받고, None만 가용값에서 제외합니다. R 함수는 수치 벡터에서 is.na가 참인 원소를 제외합니다. 입력이 검증된 실제 예제에서는 같은 가용 분모를 얻지만, 모든 객체에 두 함수가 같은 일을 한다는 뜻은 아닙니다.
Python
def available_mean(values):
valid = [x for x in values if x is not None]
return sum(valid) / len(valid) if valid else None
print(available_mean([2, None, 4, 0]))
Python 쪽에 추가로 NaN을 넣으면 이 함수가 그것을 자동 제외하지는 않습니다. R의 is.na도 무한대 Inf를 제외하지 않습니다. 결측 판정과 유한값 판정은 다르므로, 실제 계약이 유한 수치만 허용한다면 별도 검사로 Inf·NaN을 거부하거나 명시한 처리 규칙을 적용해야 합니다.
무엇을 제외했는지도 결과와 함께 반환하는 함수가 실무에서 유용합니다. 원행 수,가용값 수,제외 이유,가용 합과 평균을 함께 기록하면 값 하나만 내보냈을 때보다 오류를 찾기 쉽습니다. 다음 실제 자료 실습의 세 단계가 바로 그 정보를 따로 보여 줍니다.
Write the first contract explicitly. The actual-data Python function accepts numbers or None and excludes only None. The R function excludes values detected by is.na from a numeric vector. They agree on the validated actual inputs here, not on every possible object.
Python
def available_mean(values):
valid = [x for x in values if x is not None]
return sum(valid) / len(valid) if valid else None
print(available_mean([2, None, 4, 0]))
The Python function does not automatically exclude NaN. R is.na does not exclude Inf. Missingness and finiteness differ; a finite-numeric-input contract needs an additional check or an explicitly chosen nonfinite-value policy.
Practical summaries should report original count, available count, exclusion reason, available sum and mean. These make errors easier to diagnose than one isolated result. The actual-data trace separates those stages.
기초Foundations
37. 모든 값이 없을 때도 정상 결과와 오류를 구별한다37. Handle all-missing inputs without inventing a zero mean
가정 입력이 None,None 또는 NA,NA라면 원소는 2개 있지만 가용값은 0개입니다. 원자료가 아예 빈 경우와 원행 수는 다르지만,가용 평균의 분모는 둘 다 0입니다. 먼저 세어 본 뒤 나누어야 하는 이유입니다.
Python
values = [None, None]
valid = [x for x in values if x is not None]
answer = sum(valid) / len(valid) if valid else None
print(len(values), len(valid), answer)
출력은 원소 수 2,가용 수 0,명시한 비수치 결과 표식입니다. 그날 평균이 실제로 0이었다는 답을 만들지 않습니다. 모형이 요구하는 평균이 정의되지 않은 것과 프로그램이 예상치 못하게 충돌한 것도 구별합니다. 이 함수는 계약에 따라 그 경계를 반환한 것입니다.
나중에 표를 그릴 때 가용 수 0인 막대를 높이 0으로 그리면 “관측한 평균 0”처럼 보일 수 있습니다. 이 장의 실습은 결과 없음과 원행 수를 따로 표시합니다. 시각화에서도 분모와 미정의 상태를 보존해야 합니다.
None, None or NA, NA contains two source elements but zero available values. An empty source has another original count, though both available-mean denominators are zero. Count before dividing.
Python
values = [None, None]
valid = [x for x in values if x is not None]
answer = sum(valid) / len(valid) if valid else None
print(len(values), len(valid), answer)
The result reports original count two, available count zero and the chosen nonnumeric marker. It does not invent an observed mean zero. A deliberately handled undefined mean differs from an unexpected program failure.
A zero-height bar for no available values can wrongly suggest an observed zero. Preserve availability and undefined status in visualizations as well as calculation tables.
기초Foundations
38. 조건보다 먼저 가용성을 확인하는 짧은 경로를 쓴다38. Check availability before a value-based condition
미관측 값이 섞인 입력에서 3 이상인 값만 고르고 싶습니다. Python에서는 None을 수와 바로 비교하지 않고, 먼저 None이 아닌지 확인합니다. and의 왼쪽이 거짓이면 오른쪽 비교를 실행하지 않는 짧은 평가를 이용할 수 있습니다.
Python
values = [2, None, 4, 0]
selected = [x for x in values if x is not None and x >= 3]
print(selected)
결과는 4 하나입니다. R 예제는 가용 묶음을 먼저 만든 뒤 조건을 적용해 단계를 분리했습니다. 원래의 논리 마스크에 NA가 섞인 채 인덱싱하면 추가 NA가 결과에 남을 수 있으므로 선택 결과의 유효성과 길이를 확인합니다.
이것은 “미관측이었던 실제 값은 3 미만이다”라는 추론이 아닙니다. 값을 모르므로 가용값 조건 요약에서 제외하는 프로그래밍 규칙입니다. 전체 모집단의 3 이상 비율을 추정하려면 결측 처리의 통계적 근거를 별도로 검토해야 합니다.
Select values at least three when inputs include a marker. Python first checks that x is not None. Short-circuit and skips the numeric comparison when its left side is false.
Python
values = [2, None, 4, 0]
selected = [x for x in values if x is not None and x >= 3]
print(selected)
The selected result is four. The R example makes an available subset before filtering, keeping the stages explicit. An NA-containing logical mask can leave NA in a selected result, so inspect length and validity.
This does not infer that the unknown actual value was below three. It is a rule for summarizing available values. Estimating a population fraction requires a separate missingness argument.
기초Foundations
39. 같은 NA라도 생긴 이유를 기록한다39. Record why a marker appeared
실제 파일의 빈 칸,문자 변환 실패,범위 밖 인덱스,빈 평균 계산은 비슷한 표시를 만들 수 있지만 원인은 다릅니다. 하나의 평균 함수가 결과에서 NA만 세면 이 네 원인을 구별하지 못할 수 있습니다. 처음 생긴 단계의 원문·행 키·오류나 경고를 보관해야 합니다.
예를 들어 실제 Card의 공표 로그 미관측은 원문에서 가용값이 없던 경우입니다. R의 as.numeric("three")가 만든 NA는 코드가 문자를 수로 바꾸다 실패한 경우입니다. 존재하지 않는 다섯째 원소를 읽어 만든 NA는 선택 오류일 수 있습니다. 모두 같은 조사 미응답이라고 보고하면 자료의 문제를 잘못 진단합니다.
프로그램이 멈추면 최소 입력을 만들어 원인을 재현하세요. 3,613행 전체를 고치기 전에 문자 하나·인덱스 하나·빈 묶음 하나로 확인하는 것입니다. 원자료를 덮어쓰지 않고 변환 결과를 다른 이름에 저장하면 어떤 단계가 달라졌는지 대조하기 쉽습니다.
An original blank, failed text conversion, out-of-range index and empty mean can create similar-looking markers for different reasons. Counting final NA values alone may not distinguish them. Preserve source text, row keys and warnings/errors at the stage that created a marker.
The actual Card unavailable logs lack an available source value. R as.numeric("three") instead creates NA through failed conversion. Reading a nonexistent fifth element can create NA through selection. Calling all three survey nonresponse misdiagnoses the problem.
Reproduce failures with a minimal input before altering thousands of rows. Test one string, one index or one empty collection. Keep transformed results under another name rather than overwriting the original.
기초Foundations
40. 실습 E: 가용성·미정의·유한값을 구별한다40. Lab E: separate availability, undefined results and finiteness
먼저 관측 0이 분모에 들어갈지 예상하세요. 표식,가용 평균,표식 미처리 평균,NaN 비교,None/NA 비교,빈 객체,전체 결측,무한대,0 채움 예제를 선택할 수 있습니다. 원행 수와 유효 분모를 직접 적은 뒤 실행 기록과 대조합니다.
0 채움 예제는 오류가 무엇을 바꾸는지 보이는 가정 시연입니다. 실제 원자료를 수정하거나 권장 대체법을 인증하는 기능이 아닙니다. 미관측이 존재한다는 사실만으로 무조건 버리거나 0으로 채우는 두 선택 중 하나를 택할 수 있는 것도 아닙니다. 실제 질문과 결측 원인을 살펴야 합니다.
확인 질문: 이 표식은 원문에서 왔나요,계산이 만들었나요? 이 함수가 제외하는 것은 None인가요,is.na인 값인가요,모든 비유한값인가요? 모든 값이 없을 때 반환값과 평균 0을 분명히 나눴나요?
Predict whether observed zero enters the denominator. Choose markers, available means, unhandled means, NaN comparison, None/NA comparison, empty objects, all-missing input, infinity or zero filling. Write the original and valid counts before inspecting the archived run.
Zero filling is an explicit error/assumption demonstration. It neither modifies the actual source nor certifies an imputation method. Missingness alone does not force a choice between deletion and zero filling; the question and missingness process matter.
Ask where the marker came from, which markers the function excludes and whether that differs from excluding all nonfinite values. Distinguish an unavailable mean from an observed mean zero.
기초Foundations
41. 실제 자료도 읽기→변환→요약을 나누어 실행한다41. Run actual data through reading, conversion and summary stages
이제 작은 가정 값에서 보관한 실제 자료로 넘어갑니다. 국가·사람·점포마다 같은 세 단계를 적용합니다. 첫 단계는 모든 원행과 원행 키를 읽습니다. 둘째는 명시한 수치 열만 변환하고 원행 수·가용 수를 셉니다. 셋째는 작은 요약 함수로 가용 평균을 계산합니다.
파일 읽기를 모두 암기할 필요는 없습니다. 내려받은 예제 코드의 준비 부분을 그대로 사용하고,자료형·가용 분모·반환값을 해석하는 데 집중하세요. Python 예제는 문자열 필드를 먼저 읽고 빈 문자열만 None으로 변환합니다. R 예제는 열을 character로 읽은 뒤 지정 열만 수로 바꿉니다. UTF-8 BOM이 있는 첫 열 이름을 올바르게 읽도록 파일 인코딩도 명시했습니다. 파일과 인코딩은 다음 장들에서 더 자세히 배웁니다.
각 실행에는 입력 CSV의 SHA256과 코드 SHA256이 있습니다. 해시는 같은 바이트를 썼는지 대조하는 도구입니다. 파일이 진실인지,대표성이나 인과효과가 있는지 증명하지는 않습니다. 실제 원문과 선택 CSV의 대조,별도 Python/R 재현,화면 표시는 다른 검증 단계입니다.
Move from toy values to retained actual files with the same three-stage pattern. Read original rows and keys; convert only specified numeric fields while counting availability; then call a small summary function.
You need not memorize the file-reading setup. Use the downloadable code and focus on types, denominators and returns. Python initially reads text fields and converts only blank source values to None. R initially reads character columns and converts the intended numeric field, explicitly handling the UTF-8 BOM so that the first column name is retained. Later chapters develop files and encoding.
Each run records input and code SHA256 hashes. A hash checks content identity, not source truth, representativeness or causal identification. Raw-source comparisons, separate Python/R reproduction and displayed tables are different validation stages.
기초Foundations
42. 국가 사례: 지표 단위 변환을 리스트 반복과 혼동하지 않는다42. Country example: unit conversion is not list repetition
실제 World Bank 2024년 선택 16국의 GDP 열은 2015년 불변 USD/인 단위입니다. 호주의 원값 61,486.38147544를 10,000으로 나누면 약 6.148638147544가 됩니다. 새 눈금의 한 단위는 10,000USD/인입니다. 원 GDP가 바뀐 것이 아니라 표현 눈금이 달라졌습니다.
Python
gdp = [61486.38147544, 9566.74518687619]
scaled = [value / 10000 for value in gdp]
print(scaled)
R
gdp <- c(61486.38147544, 9566.74518687619)
scaled <- gdp / 10000
print(scaled)
위 두 값은 실제 호주·브라질의 일부 값을 직접 적어 보는 예입니다. 전체 16행을 읽는 실행은 실제 자료 실습에 따로 있습니다. Python 기본 리스트에 정수를 곱해 반복한 결과를 “모든 국가 지표의 단위가 바뀌었다”고 해석하지 않습니다. 변환 후 길이가 원 16개인지 먼저 확인해야 합니다.
이 고정 16국 프레임의 가용 원값 평균은 약 31,100.23857217USD/인입니다. 국가를 균등 가중한 지표 평균이며 세계 개인소득 평균이 아닙니다. 호주 sourceRow=2161은 보관 API 배열의 원위치이고,현재 16행의 첫 위치와 다른 키라는 점도 유지합니다.
The actual 2024 World Bank GDP-per-person field uses constant-2015 USD/person. Dividing Australia’s 61,486.38147544 by ten thousand gives about 6.148638147544. One new coordinate unit is ten thousand USD/person. This changes representation, not GDP itself.
Python
gdp = [61486.38147544, 9566.74518687619]
scaled = [value / 10000 for value in gdp]
print(scaled)
R
gdp <- c(61486.38147544, 9566.74518687619)
scaled <- gdp / 10000
print(scaled)
These manually written values illustrate actual Australian and Brazilian fields. The actual-data trace separately reads all sixteen rows. Repeating a Python basic list is not an elementwise unit conversion. Check that transformed length remains sixteen.
The fixed frame’s unweighted original-value mean is about 31,100.23857217 USD/person. It is an equal-country indicator mean, not worldwide individual income. Australia’s sourceRow 2161 identifies its archived API position, not its first position in the selected sixteen rows.
기초Foundations
43. 사람 사례: 로그 임금의 원행과 3,010개 분모를 보존한다43. Person example: preserve source rows and the 3,010-value denominator
Card 원자료에서 읽은 사람 기록은 3,613개입니다. 가용 로그 임금은 3,010개,미관측은 603개입니다. 함수의 출력부터 믿는 대신,첫 단계의 원행 수와 둘째 단계의 가용 수가 각각 이 값인지 확인합니다. 결측 표식을 제외한 가용 평균은 약 6.261831917744입니다.
Python의 읽기 함수는 CSV의 빈 문자열에 None을 붙이며,0이라는 문자열은 float 변환으로 수치 0이 됩니다. 이 규칙은 실제 로그 가용값을 임의로 0으로 만들지 않습니다. R도 같은 원행을 유지한 채 빈 원문을 NA로 읽고 가용 분모를 계산합니다. 두 언어의 원문과 단위가 같은지 확인한 다음 소수 출력의 작은 차이를 비교하세요.
lwage76은 1976년 시간당 임금(센트/시간)의 원문 극단값 정리 로그 변수입니다. 로그 평균 자체를 센트·달러의 산술 임금평균이라 부르지 않습니다. 이 짧은 프로그램이 표본 선택,원문 정리,미관측 603명의 값을 해결하거나 교육의 인과수익률을 추정한 것은 아닙니다.
The Card source contains 3,613 person rows, 3,010 available log wages and 603 unavailable values. Check the first-stage source count and second-stage available count before trusting the function output. The available-value mean is about 6.261831917744.
The Python reader maps blank text to None but maps text “0” to numeric zero. It does not replace unavailable source logs with observed zero. R preserves the same original rows, reads blanks as NA and uses the available denominator. Match source fields and units before discussing small decimal-display differences.
The source-trimmed lwage76 variable records logs of 1976 hourly wages in cents/hour. Its mean is not an arithmetic currency-wage mean. This short program does not repair selection, trimming or the 603 missing values, nor estimate a causal schooling return.
기초Foundations
44. 점포 사례: 코드 407 두 행을 지우지 않고 함수에 넣는다44. Store example: keep both source rows with code 407
실제 Card–Krueger 보관 자료는 원행 410개입니다. 전후 FTE가 모두 가용한 짝은 384개이고,26개는 완전한 변화 계산에 필요한 성분이 부족합니다. FTE는 전일제+0.5×시간제+관리자입니다. 필요한 성분이 없을 때 그 성분을 0명이라고 추측해 더하지 않습니다.
점포 코드 407은 원행 42와 168에 각각 나타납니다. 원행 42는 PA·체인2·11→11이고,원행 168은 NJ·체인4·12→14.5입니다. 둘의 변화는 0과 2.5FTE입니다. 동일한 코드가 보였다는 이유로 하나를 지우면 원자료를 잘못 바꾸게 됩니다. 현재 배열의 위치 대신 원행 키·코드·집단을 함께 확인해야 합니다.
완전 짝의 단순 평균 변화는 −541/7680≈−0.07044270833FTE입니다. 이는 가용 짝들의 관측 요약입니다. 양수·음수 변화의 평균을 계산하는 함수가 정상 실행되었다고 정책 인과효과나 점포 iid가 확인된 것은 아닙니다. 짝 구조·결측·주별 비교의 추론은 별도 모형과 설계가 필요한 질문입니다.
The retained Card–Krueger file has 410 original rows. Both-wave FTE is available for 384 pairs; twenty-six lack components needed for a complete change. FTE=full-time+0.5×part-time+managers. Unavailable components are not assumed to be zero people.
Store code 407 appears at source rows 42 and 168. Row 42 is PA, chain two, FTE eleven→eleven; row 168 is NJ, chain four, twelve→fourteen and a half. Changes are zero and 2.5 FTE. Equal codes alone do not justify deletion. Inspect source key, code and group together rather than relying on current array position.
The complete-pair unweighted mean change is −541/7680≈−0.07044270833 FTE. It is an observed available-pair summary. Successfully computing it does not establish a causal policy effect or iid stores. Pairing, missingness and state comparisons require additional inferential design.
기초Foundations
45. 실습 F: 실제 파일의 세 단계를 확인한다45. Lab F: inspect three stages on actual files
먼저 세 자료 중 하나와 코드 언어를 고릅니다. 읽기 단계에서 원행·첫 원행 키를 확인하고,변환 단계에서 전체·가용·미관측 개수를 확인한 다음,함수 요약 단계에서 평균과 단위를 읽으세요. 중간 단계까지만 실행했는데 아직 answer가 없는 것은 오류가 아닙니다.
변수 표의 긴 실제 벡터는 화면에서 일부만 보여 줄 수 있지만 원파일과 내려받은 코드는 유지합니다. 잘린 표시를 실제로 몇 행만 분석했다는 뜻으로 읽지 않습니다. 국가의 API 원위치,사람의 원행,점포의 407 두 원행도 따로 확인할 수 있습니다.
이 화면은 보관된 실제 실행의 단계 기록입니다. 새로운 임의 코드를 실행하거나 새로운 자료를 수집하지 않습니다. 수정한 코드는 실제 런타임의 새 프로세스에서 처음부터 실행하고,입력 해시·원행 수·가용 분모·출력을 다시 대조하세요.
Choose a dataset and code language. In the reading stage inspect source count and first source key. In conversion inspect original, available and missing counts. In the summary stage read the function result and units. No answer before its step has run is not a failure.
Long actual vectors can be truncated for display while the complete input and downloadable code remain retained. Display truncation does not mean only those few rows were analyzed. Check API positions, original person rows and both source rows with store code 407.
This is a trace of archived actual execution, not arbitrary live code or new data collection. Run edited code from the beginning in a fresh real process and compare input hashes, source count, available denominator and output again.
기초Foundations
46. 작은 검산은 실행 성공과 질문의 타당성을 함께 확인한다46. Small checks test both execution and the intended question
평균 함수가 2,4,6에서 4를 돌려주는지 손으로 확인합니다. 같은 값 4,4를 주면 4인지,0을 포함한 0,4는 2인지,모두 미관측이면 약속한 표식을 반환하는지도 확인합니다. 정답을 모르는 큰 파일만 반복 실행하는 것보다 작은 반례가 오류 위치를 더 잘 보여 줄 수 있습니다.
Python
def available_mean(values):
valid = [x for x in values if x is not None]
return sum(valid) / len(valid) if valid else None
assert available_mean([2, 4, 6]) == 4
assert available_mean([0, 4]) == 2
assert available_mean([None, None]) is None
print("checks passed")
검사가 통과하면 적어 둔 작은 사례에서 코드가 약속대로 작동했다는 근거가 됩니다. 가능한 모든 자료형·모든 입력·과학적 해석을 증명한 것은 아닙니다. 예를 들어 코드가 정확하게 평균을 구해도 서로 다른 단위나 엉뚱한 관측 단위를 섞었다면 원래 질문의 답은 아닐 수 있습니다.
Check the mean of 2, 4, 6 by hand, then equal values, observed zero and all-missing inputs. A small counterexample can identify a bug more clearly than rerunning a large file with an unknown answer.
Python
def available_mean(values):
valid = [x for x in values if x is not None]
return sum(valid) / len(valid) if valid else None
assert available_mean([2, 4, 6]) == 4
assert available_mean([0, 4]) == 2
assert available_mean([None, None]) is None
print("checks passed")
Passing checks supplies evidence for those specified cases, not every possible input or scientific interpretation. A correctly computed mean can still mix incompatible units or answer the wrong observation-unit question.
기초Foundations
47. 실제 국가·사람·점포의 코드와 자료형 사례47. Actual country, person and store type/function cases
국가 사례 · 숫자로 보이는 글자와 계산 가능한 양
World Bank 실제 2024년 선택 16국가를 ISO 코드 순서로 읽습니다. code는 국가 코드 문자열, yearText는 원 전송 문자열, sourceRow는 보관한 API 응답 안의 원행 위치, valueSourceText는 GDP의 십진 문자열입니다. 원행 위치에 정수형을 쓴다고 그것이 평균을 낼 경제량이 되지는 않습니다. 식별자와 값의 자료형·의미를 함께 적어야 합니다.
첫 세 실제 국가 · 원 전송값과 단위 변환의 결과
국가 문자열
원행 위치
GDPpc 십진 문자열
명시적 ÷10000 결과
AUS
2161
61486.38147544
6.14863815
BRA
2206
9566.74518687619
0.95667452
CAN
2251
45061.3864587285
4.50613865
GDPpc 원 단위는 2015년 불변 USD/인입니다. 10000으로 나누면 한 단위가 불변 10,000USD/인이 됩니다. 단위가 달라졌을 뿐 실제 GDP가 성장하거나 줄어든 것은 아닙니다. float/double 계산은 유한 정밀도이고 CSV의 원 십진 문자열과 Fraction 검산값은 별도 보존합니다. 한영 표시를 바꿀 때도 ISO·지표 코드·원행 키를 번역하거나 재번호하지 않습니다.
gdp = [float(row['valueSourceText']) for row in rows]
scaled = [value / 10000 for value in gdp]
print(len(gdp), len(scaled))
gdp <- as.numeric(rows$valueSourceText)
scaled <- gdp / 10000
print(c(length(gdp), length(scaled)))
이 코드의 rows는 제공한 국가 CSV를 읽어 만든 행 묶음입니다. Python의 리스트에 *2를 하면 목록을 두 번 반복하지만, R의 숫자 벡터에 *2를 하면 각 값을 두 배로 만듭니다. Python에서 각 값을 바꾸려면 [2*x for x in gdp]처럼 명시합니다. 합계가 둘 다 두 배라는 사실만 검사하면 목록을 잘못 반복한 오류를 놓칠 수 있어 길이와 각 값도 확인해야 합니다.
실제 앞 세 GDP에 적용한 연산 계약
연산
입력 길이
출력 길이
개별 값의 뜻
원 세 값
3
3
실제 관측값
Python 목록 *2
3
6
관측값 반복
Python [2*x for x in 목록]
3
3
가정한 산술 변환
R 숫자 벡터 *2
3
3
가정한 산술 변환
먼저 생각한 뒤 풀이 보기: 국가 코드가 숫자로 되어 있으면 자동으로 평균을 내도 될까요?
아닙니다. 숫자로 저장된 코드도 이름표일 수 있습니다. 여기 ISO는 문자열로 유지하고, sourceRow도 추적 키로 씁니다. 수치 계산은 명시적으로 정한 GDP 변수와 단위에만 적용합니다. 언어의 형 변환이 연구 질문의 의미까지 판단해 주지는 않습니다.
사람 사례 · 결측을 입력으로 받는 작은 요약 함수
Card 원 3613개 행의 lwage76은 1976년 시간당 임금(센트)의 원 극단값 정리 로그 변수입니다. 3010개가 가용하고603개는 결측입니다. 원 전송 빈칸을 Python에서는 None, R에서는 NA_real_로 명시해 옮깁니다. 이 둘의 모든 언어 동작이 같다는 뜻은 아닙니다. 원 결측을 값0으로 바꾸지도, 유효한 관측0을 결측으로 버리지도 않습니다.
def summary_present(values):
# Contract: finite numbers or None.
good = [x for x in values if x is not None]
return {
'n_total': len(values),
'n_valid': len(good),
'mean': sum(good) / len(good) if good else None,
}
result = summary_present(log_wages)
print(result)
summary_present <- function(values) {
# Contract here: finite numeric values or NA.
good <- values[!is.na(values)]
list(n_total = length(values), n_valid = length(good),
mean = if (length(good)) mean(good) else NA_real_)
}
result <- summary_present(log_wages)
print(result)
log_wages는 제공한 원 사람 CSV의 전체3613행을 명시적으로 읽은 값 목록입니다. 이 함수는 바깥의 옛 평균에 의존하지 않고 입력을 받아 결과를 반환합니다. 화면에 print로 보인 것과 반환된 객체는 구별합니다. 가용 값이 하나도 없을 때에는 평균을0으로 꾸미지 않고 None/NA를 돌려줍니다. 원자료에는 없는 Inf 같은 값을 포함한 범용 입력 검증은 별도 계약이 필요합니다.
실제 원행을 다시 읽은 함수 요약 · 소수 반올림
전체 입력 수
가용 분모
결측 수
가용 로그 평균
잘못0대체한 평균
3613
3010
603
6.261831918
5.216748982
먼저 생각한 뒤 풀이 보기: if x로 가용 값을 고르면 더 짧지 않나요?
Python의 if x는 None뿐 아니라0도 거짓으로 취급하므로 일반 숫자 자료에서 유효0까지 버릴 수 있습니다. 여기서는 x is not None처럼 결측 계약을 검사합니다. R도 x==NA로 판정하지 않고 is.na를 사용합니다. NA, NaN, NULL과 Python None/NaN은 길이·비교·계산 동작이 달라 구분해서 실습합니다.
점포 사례 · 같은 코드와 다른 원행을 함수가 구별해야 한다
NJ/PA 원410행에서 store코드는409개뿐입니다. 코드407은 원행42와168에 각각 있고 서로 다른 체인·주·고용 값을 갖습니다. code를 문자열로 둬도 자동으로 고유 키가 되지 않습니다. 이 장은 원행 위치를 보존한 작은 입력 함수부터 배우며, 뒤 정리·조인 장에서 중복 키 관계를 더 다룹니다. 두 행을 합치거나 하나를 지우지 않습니다.
원 코드407의 실제 두 행
원행 정수 키
원 코드 문자열
체인 코드
주
전 FTE
후 FTE
같은 행의 변화
42
407
2
PA
11.0
11.0
0
168
407
4
NJ
12.0
14.5
5/2
FTE는 전일제+0.5×시간제+관리자로 계산하며 어느 구성요소가 비면 해당 시점 FTE를 만들지 않습니다. 전후가 둘 다 있어야 같은 원행의 after−before를 계산합니다. 전체410행 중 가용 변화는384개, 결측 변화는26개입니다. 코드나 주 표시의 평균은 고용 평균을 대신하지 않으며 이 관측 변화도 정책 인과효과가 아닙니다.
def paired_change(before, after):
if before is None or after is None:
return None
return after - before
# Keep sourceRow/code next to the computed value.
changes = [paired_change(r['before'], r['after']) for r in rows]
paired_change <- function(before, after) {
if (is.na(before) || is.na(after)) return(NA_real_)
after - before
}
# For scalar pairs, preserve sourceRow/code beside each result.
changes <- mapply(paired_change, rows$before, rows$after)
원행 키42를 Python 목록의 위치42로 바로 쓰면 같은 행을 가리키지 않을 수 있습니다. 원행 키는1부터 매긴 출처 위치이고 Python 목록 인덱스는0부터입니다. R은 보통1부터 인덱싱하지만 정렬·필터 뒤 목록 위치가 원행 키와 같다는 보장은 없습니다. 명시적으로 보존한 sourceRow 열로 찾고 실제 값과 코드를 함께 확인하세요. 코드 실행 순서를 바꾸거나 오래된 변수를 남겨 두면 정답처럼 보이는 옛 결과가 출력될 수 있어 새 프로세스에서 입력→함수→계산→출력 순서로 재현합니다.
먼저 생각한 뒤 풀이 보기: 브라우저 버튼에서 Python 코드를 고쳐 무제한 실행하는 실습인가요?
이 장의 브라우저는 실제 언어 런타임에서 미리 실행한 유한 코드 카탈로그의 기록을 선택·추적합니다. 임의 Python/R을 실행한다고 주장하지 않습니다. 직접 코드를 바꾸려면 제공한 실행 파일을 내려받아 해당 Python/R 환경의 새 프로세스에서 실행하고 버전·입력·코드 해시와 출력·오류를 기록하세요.
Country case · Text that looks numeric and quantities we can calculate
Read sixteen actual 2024 World Bank countries in ISO-code order. code is a country-code string, yearText preserves transport text, sourceRow locates an original row in the archived API response, and valueSourceText preserves decimal GDP text. An integer row position is not an economic quantity whose average is meaningful. Record both the type and the meaning of each field.
First three actual countries · source text and unit conversion
Country string
Source-row position
GDPpc decimal source text
Explicit divide-by 10000 result
AUS
2161
61486.38147544
6.14863815
BRA
2206
9566.74518687619
0.95667452
CAN
2251
45061.3864587285
4.50613865
The source unit is constant-2015 USD/person. Dividing by 10000 changes the unit to 10,000 constant-2015 USD/person; actual GDP has not grown or fallen. Float/double arithmetic has finite precision. Preserve source decimal text and a separate Fraction verification value. Switching display language does not translate ISO/indicator codes or renumber source keys.
gdp = [float(row['valueSourceText']) for row in rows]
scaled = [value / 10000 for value in gdp]
print(len(gdp), len(scaled))
gdp <- as.numeric(rows$valueSourceText)
scaled <- gdp / 10000
print(c(length(gdp), length(scaled)))
Here rows means the records loaded from the provided country CSV. Multiplying a Python list by 2 repeats the container; multiplying an R numeric vector by 2 doubles each element. Python elementwise transformation can use [2*x for x in gdp]. Both operations double the sum, so checking only the sum can miss a container-repetition error. Check length and individual values too.
Operations on the first three actual GDP values
Operation
Input length
Output length
Meaning
Original three values
3
3
Actual observations
Python list *2
3
6
Repeated observations
Python [2*x for x in list]
3
3
Chosen arithmetic transform
R numeric vector *2
3
3
Chosen arithmetic transform
Think first, then reveal: If an identifier contains digits, should it automatically be averaged?
No. Numeric storage can still represent a label. Keep ISO strings and use sourceRow for traceability. Apply arithmetic to an explicitly chosen quantity and unit. Type conversion does not determine the scientific meaning of a variable.
Person case · A small summary function that preserves missing inputs
Card’s original 3613 records contain source-trimmed logs of 1976 hourly wages in cents/hour:3010 are available and 603 are missing. Explicitly map source blanks to Python None or R NA_real_. These markers do not have identical semantics in every language operation. Do not replace unavailable values with zero, or discard a valid observed zero as missing.
def summary_present(values):
# Contract: finite numbers or None.
good = [x for x in values if x is not None]
return {
'n_total': len(values),
'n_valid': len(good),
'mean': sum(good) / len(good) if good else None,
}
result = summary_present(log_wages)
print(result)
summary_present <- function(values) {
# Contract here: finite numeric values or NA.
good <- values[!is.na(values)]
list(n_total = length(values), n_valid = length(good),
mean = if (length(good)) mean(good) else NA_real_)
}
result <- summary_present(log_wages)
print(result)
log_wages is loaded explicitly from all 3613 rows in the provided person CSV. The function receives its input and returns a result rather than relying on an old external mean. Printed display differs from the returned object. With no available values, return None/NA rather than inventing a zero mean. General inputs such as Inf, absent from these source values, need a separate validation contract.
Function summary from re-read actual records · rounded
Total inputs
Valid denominator
Missing
Available log mean
Invalid zero-fill mean
3613
3010
603
6.261831918
5.216748982
Think first, then reveal: Why not use if x to keep valid values?
Python truth testing excludes both None and zero, so a general numeric dataset can lose valid zeros. Test the missingness contract explicitly with x is not None. R uses is.na rather than x==NA. R NA, NaN and NULL, and Python None/NaN differ in length, comparison and arithmetic behavior; study them separately.
Establishment case · Functions must preserve distinct rows sharing a code
The 410 original NJ/PA rows contain 409 distinct store codes. Code 407 appears at source rows 42 and 168 with different chains, states and employment values. Keeping code as a string does not make it unique. Start with small functions preserving source positions; later cleaning/join chapters examine key relationships. Neither merge these two rows nor delete one.
Two actual source rows coded 407
Source-row integer key
Original code string
Chain code
State
Before FTE
After FTE
Within-row change
42
407
2
PA
11.0
11.0
0
168
407
4
NJ
12.0
14.5
5/2
FTE is full-time staff +.5×part-time staff +managers; an unavailable component makes that wave unavailable. Compute after−before only when both waves exist within the same original row. There are 384 available changes and 26 unavailable changes among 410 records. An average of codes or state indicators is not mean employment, and these observed changes are not policy causal effects.
def paired_change(before, after):
if before is None or after is None:
return None
return after - before
# Keep sourceRow/code next to the computed value.
changes = [paired_change(r['before'], r['after']) for r in rows]
paired_change <- function(before, after) {
if (is.na(before) || is.na(after)) return(NA_real_)
after - before
}
# For scalar pairs, preserve sourceRow/code beside each result.
changes <- mapply(paired_change, rows$before, rows$after)
Using source-row key 42 directly as Python list index 42 may select a different row. Source keys are one-based archived positions, while Python list indices start at zero. R usually indexes from one, but sorting/filtering can still separate list position from source-row key. Look up the preserved sourceRow field and check code and value together. Reordered execution or stale variables can display plausible old answers; reproduce in a fresh process in input→function→calculation→output order.
Think first, then reveal: Do the browser buttons execute arbitrary edited Python/R code?
No. They select and trace a finite catalog of actual recorded language-runtime executions. To modify code freely, download the runnable files, start a fresh Python/R process, and record runtime version, input/code hashes, output and errors. Recorded execution is distinct from unrestricted live execution.
기초Foundations
48. 공식 문서를 읽고 새 프로세스에서 다시 설명한다48. Read primary documentation and explain a fresh run
Python 3.12 공식 튜토리얼 3장에서 수·문자열·리스트의 짧은 예를 읽고, 함수 정의에서 인자와 반환을 확인하세요. 웹 문서의 패치 버전과 보관 실행의 3.12.14가 다를 수 있으므로 실제 실행 버전은 카탈로그 기록을 기준으로 적습니다.
R 공식 입문서에서는 §2.1 벡터·할당,§2.5 미관측,§2.7 인덱스,§10 함수의 기본 설명부터 읽습니다. 현재 웹 문서의 버전과 이 장의 R 4.5.1 실행은 구별합니다. 고급 모형 예제를 한꺼번에 이해해야 이 장을 시작할 수 있는 것은 아닙니다.
마지막 과제는 내려받은 코드 하나를 새 프로세스에서 실행하고 다른 사람에게 설명하는 것입니다. 입력 원행과 단위,문자에서 수치로 바꾼 규칙,가용 분모,반환값,실제 출력,실행 버전을 각각 말해 보세요. 다음 장은 이 코드를 어떤 폴더와 파일에 보관하고 수정 이력을 남길지 이어갑니다.
Read the short numbers, strings and lists examples in the official Python 3.12 tutorial, then inspect arguments and returns in function definitions. The website’s patch version can differ from the archived 3.12.14 runtime; record the version actually executed.
In the official R introduction, start with §2.1 vectors/assignment, §2.5 missing values, §2.7 indexing and §10 function basics. Distinguish the current manual from this chapter’s recorded R 4.5.1. Understanding every advanced model example is not a prerequisite.
Run one downloaded file in a fresh process and explain its source rows, units, text conversion, available denominator, returned value, displayed output and runtime version. The next chapter develops folders, files and change history for this code.
자료 묶음을 풀고 코드와 실제데이터 폴더를 함께 두세요. 터미널에서 코드 파일이 있는 폴더로 이동해 아래 명령을 실행합니다. 코딩이 처음이라면 손계산과 웹 실습을 먼저 하고, 데이터 사이언스 입문에서 코드를 배운 뒤 돌아와도 됩니다.Extract the bundle, keeping the scripts beside the data folder. In a terminal, enter the script folder and run the commands below. Beginners can complete hand calculations and browser labs first, returning to code after studying introductory data science.
결과 파일은 각 코드에 지정된 결과 폴더에 저장됩니다. CSV 원자료는 덮어쓰지 않습니다.Result files are saved in the result directory specified by each script; the input CSVs are not overwritten.
영상·학자·함께 읽기Videos, thinkers and guided reading
본문의 질문을 넓히는 선택 학습입니다. 영상을 보기 전 질문을 먼저 읽고, 자신의 답을 쓴 뒤 해설과 비교하세요. 자료의 언어·선수 지식은 각 항목에 표시했습니다.Optional extensions to the chapter. Read the question first, write your answer, then compare with the explanation. Language and prerequisites are indicated below.
MIT · 계산·이름·값·자료형의 첫 만남MIT · First steps with computation, names, values and types
MIT OCW 6.0001 · Ana Bell · Lecture 1 · 2016
기본 Python 문법과 자료 구조를 소개하는 공식 강의입니다. 원자료의 코드·행 키·GDP 값이 각각 어떤 의미와 자료형을 갖는지 적으며 따라가세요. 오래된 강의의 환경과 현재 실행 버전은 별도로 기록합니다.Follow the introductory syntax/data-structure lecture while writing down the meaning and type of source codes, row keys and GDP values. Record the historical lecture environment separately from the current execution runtime.
교재 안의 YouTube 플레이어에서 재생합니다. 원영상에서 제공하는 자막은 플레이어의 CC·설정에서 선택할 수 있습니다.Playback stays in this chapter’s YouTube player. Available captions can be selected through CC/settings.
보고 읽은 뒤 답하기Respond after watching/reading실행은 되는데 연구 질문과 다른 답을 낼 수도 있나요?Can code run successfully while answering the wrong research question?
생각을 점검하는 해설Check your reasoning
가능합니다. 목록 반복·잘못된 분모·코드 평균처럼 문법상 유효해도 의미가 다른 연산이 있습니다.Yes. List repetition, a wrong denominator or averaging codes can be syntactically valid but substantively wrong.
존 체임버스 · 자료분석을 위한 언어와 객체John Chambers · Languages and objects for data analysis
Stanford Department of Statistics · official profile
공식 소개의 S 언어·R 프로젝트와 과학 자료분석 소프트웨어 관심을 읽습니다. 데이터 값과 이름·객체·그래픽을 함께 다루는 설계가 분석의 추적 가능성에 어떻게 연결되는지 생각해 보세요.Read the profile’s S language, R project and scientific-data software interests. Consider how connecting values, names, objects and graphics supports traceable analysis.
보고 읽은 뒤 답하기Respond after watching/reading언어가 같으면 분석의 의미도 자동으로 같을까요?Does using the same language ensure the same analytical meaning?
생각을 점검하는 해설Check your reasoning
아닙니다. 입력·함수·단위·분모·실행 상태를 명시해야 같은 질문을 계산했는지 확인할 수 있습니다.No. Specify inputs, functions, units, denominators and execution state to check that the same question was computed.
Python 공식 · 숫자·문자열·목록과 함수Official Python · Numbers, strings, lists and functions
Python3.12 tutorial §3.1 and §4.8
§3.1에서 숫자·문자열·목록을 구분하고 §4.8의 입력·반환·지역 이름을 이어 읽습니다. 목록 반복과 각 값의 산술 변환을 다르게 쓰고, 출력과 반환을 구분해 실제 CSV의 짧은 요약 함수를 직접 설명해 보세요.Distinguish numbers, strings and lists in §3.1, then inputs, returns and local names in §4.8. Explain repetition versus elementwise transformation and output versus return using the actual-data summary function.
보고 읽은 뒤 답하기Respond after watching/readingsum이 맞으면 입력 길이 검사도 생략할까요?If the sum is correct, may length checks be omitted?
생각을 점검하는 해설Check your reasoning
아닙니다. 목록 반복과 값 두 배는 합이 같아도 입력·출력의 의미가 다릅니다.No. Repetition and doubling can have the same sum but different record semantics.
R 공식 · 벡터 산술·결측·함수Official R · Vector arithmetic, missing values and functions
R Core manual §2.2/2.5/2.7/10 and base NA help
원자 벡터의 원소별 산술과 재활용, 결측 표시·인덱스·함수를 읽습니다. 공식 온라인 문서의 버전과 로컬 실행 R 버전을 구별하며, 이 교재의 결과는 저장된 실제 실행 기록으로 확인합니다.Read elementwise vector arithmetic/recycling, missing markers, indexing and functions. Distinguish the online manual version from the local R runtime; verify this chapter through recorded real executions.
보고 읽은 뒤 답하기Respond after watching/readingNA와 문자열 "NA", NULL은 길이와 연산이 모두 같나요?Are NA, the string "NA", and NULL identical in length and operations?
생각을 점검하는 해설Check your reasoning
아닙니다. 해당 객체의 typeof·length·is.na 결과를 각각 확인해야 합니다.No. Check each object’s typeof, length and is.na results separately.
연습문제 · 계산에서 설명과 증명까지Exercises: calculation, explanation and proof
먼저 혼자 풀고 풀이를 여세요. 숫자와 함께 단위·포함 기준·계산 이유를 확인하세요.Attempt each problem before opening its solution. Check units, inclusion rules and the reason for the calculation.
1. 숫자와 문자의 두 답Two answers for numbers and text
Python에서 3 + 2와 "3" + "2"를 각각 계산하면 무엇인가요? 둘째를 수치 합으로 읽지 않는 이유를 설명하세요.
Evaluate Python 3 + 2 and "3" + "2". Why is the second not numeric addition?
풀이와 확인할 이유Solution and explanation
첫 결과는 정수 5, 둘째는 문자 "32"입니다. 피연산자의 종류가 다르며 문자열의 +는 여기서 연결입니다. 숫자 모양만 보고 원자료를 모두 수로 해석하면 식별자 의미를 잃을 수 있습니다.
The results are integer 5 and text "32". Operand types differ, and string + concatenates here. Digit-looking source identifiers should not automatically be treated as quantities.
2. 할당 뒤 다시 바꾼 이름Rebinding after an assignment
두 언어의 숫자 예에서 x에 3, y에 x를 할당한 뒤 x를 9로 바꿉니다. x와 y는 각각 무엇인가요? 이것만으로 모든 객체의 할당이 독립 복사라고 결론내려도 되나요?
In the numeric examples, bind x to 3, y to x, then rebind x to 9. What are x and y? Does this prove independent copying for every object?
풀이와 확인할 이유Solution and explanation
x는 9, y는 3입니다. y는 당시의 숫자 값에 연결되었습니다. 이 숫자 재할당 예를 변경 가능한 모든 객체의 복사·공유 규칙으로 일반화할 수는 없습니다.
They are nine and three. The example concerns numeric rebinding; it does not establish copying or sharing behavior for every mutable object.
3. 증가식의 읽는 순서Reading an increment in order
기존 count가 4일 때 count = count + 1은 어떤 순서로 처리되나요? 새 프로세스에서 count가 없다면요?
With count already equal to four, how is Python count = count + 1 evaluated? What if count is absent in a fresh process?
풀이와 확인할 이유Solution and explanation
오른쪽 기존 값 4를 읽고 1을 더해 5를 만든 뒤 같은 이름에 연결합니다. 이름을 만들지 않은 새 프로세스에서는 오른쪽을 읽을 수 없어 오류가 납니다. 수학 방정식 count=count+1을 푸는 작업이 아닙니다.
Read four on the right, compute five and rebind the name. An absent name raises an error while evaluating the right side. This is not solving a mathematical equation count=count+1.
4. 같음 비교의 결과Results of comparisons
x가 3일 때 x == 3과 x > 4의 결과는 무엇인가요? 할당과 어떻게 다른가요?
When x is three, what are x == 3 and x > 4? How do they differ from assignment?
풀이와 확인할 이유Solution and explanation
참과 거짓입니다. 비교는 논리 결과를 계산하며 x를 새 값에 연결하는 할당이 아닙니다. Python과 R의 참·거짓 출력 철자가 달라도 이 논리는 같습니다.
They are true and false. Comparison computes a logical result rather than rebinding x. Language-specific display spelling does not change this logic.
5. 길이와 합Length versus sum
가정 자료 2,4,6,6의 길이와 합을 구하세요. 같은 값 6이 두 번 있다고 원소 수를 줄이나요?
Find the length and sum of toy values 2, 4, 6, 6. Should the repeated six reduce the length?
풀이와 확인할 이유Solution and explanation
길이는 4, 합은 18입니다. 반복 값도 각각 한 원소로 남습니다. 서로 다른 값의 개수 3은 다른 요약입니다. 실제 원행이 중복인지 확인하지 않고 같은 값만 보고 지우지 않습니다.
The length is four and sum eighteen. The number of distinct values, three, is another summary. Equal values alone do not justify deleting actual source records.
6. 이전 답과 새 입력An old answer and new input
rows가 2,4,6일 때 평균 answer=4를 저장한 뒤 rows를 10,20으로 바꾸었습니다. answer도 15가 되나요? 어떻게 현재 입력에 맞추나요?
Store mean answer=4 from rows 2, 4, 6, then replace rows by 10, 20. Does answer become fifteen? How do you update it?
풀이와 확인할 이유Solution and explanation
자동으로 바뀌지 않아 answer는 4입니다. 현재 rows를 인자로 평균 함수를 다시 호출해 answer에 반환값 15를 할당해야 합니다. 오류가 없다는 사실만으로 최신 입력의 답이라는 보장은 없습니다.
The stored answer remains four. Call the mean function again on current rows and assign its returned fifteen. Absence of an error does not establish that an answer uses current input.
7. 네 셀의 두 순서Two orders of four cells
셀1은 rows=2,4,6, 셀2는 평균 함수 정의, 셀3은 answer 계산, 셀4는 rows=10,20입니다. 1234와 1243의 마지막 answer를 비교하세요.
Cell 1 sets rows to 2, 4, 6; cell 2 defines average; cell 3 computes answer; cell 4 sets rows to 10, 20. Compare final answers for orders 1234 and 1243.
풀이와 확인할 이유Solution and explanation
1234는 answer=4를 만든 뒤 입력만 바꾸므로 마지막 answer는 오래된 값 4입니다. 1243은 입력을 바꾼 뒤 계산하므로 15입니다. 같은 네 셀을 한 번씩 썼다는 사실만으로 실행 순서의 영향이 사라지지 않습니다.
Order 1234 stores four before changing input, leaving a stale answer. Order 1243 computes fifteen after the input change. Using the same four cells once each does not remove order dependence.
8. 오류 뒤 계속된 기록의 의미What continuing after an error means
추적 실습이 아직 함수가 없는 셀3의 오류를 기록하고 셀1로 진행합니다. 일반 Python/R 스크립트도 처리하지 않은 오류 뒤 항상 계속된다는 뜻인가요?
The trace records cell 3 failing before the function exists, then advances to cell 1. Does every ordinary Python/R script continue after an unhandled error?
풀이와 확인할 이유Solution and explanation
아닙니다. 추적 기록기는 셀별 오류를 잡고 다음 셀을 실행하도록 특별히 작성했습니다. 일반 스크립트의 처리하지 않은 오류는 실행을 중단할 수 있습니다. 기록기의 제어 규칙과 언어 자체의 일반 동작을 구별합니다.
No. The recorder explicitly catches each cell error before continuing. An ordinary unhandled error can stop a script. Recorder control policy is not a universal language rule.
9. 식별자 03Identifier 03
점포 코드 "03"을 숫자 3으로 변환했습니다. 자료형 변환에 성공했으므로 평균 점포 코드가 의미 있는 연속량이 되나요?
The store identifier "03" converts successfully to numeric three. Does this make average store code a meaningful continuous measurement?
풀이와 확인할 이유Solution and explanation
아닙니다. 변환 가능성과 측정 의미는 다릅니다. 식별자 앞자리 0도 잃을 수 있습니다. 원문과 자료 사전의 코드 정의를 보존하고, 수치 평균이 질문에 의미가 있는지 따로 판단합니다.
No. Conversion success does not determine measurement meaning, and the leading zero may be lost. Preserve source text and the dictionary’s identifier definition.
10. 정수 리터럴의 언어 차이Integer literals in two languages
Python의 3과 3.0, R의 3L과 3은 각각 어떤 기본 자료형인가요?
Give the basic types of Python 3 and 3.0, and R 3L and 3.
풀이와 확인할 이유Solution and explanation
Python은 int와 float, R은 integer와 double입니다. 같은 수치 3을 나타내도 내부 종류가 다를 수 있습니다. 실제 실행의 type/typeof 출력으로 확인합니다.
They are Python int and float, and R integer and double. Equal numerical values need not have identical internal types.
11. 음수의 바닥 나눗셈Floor division of a negative value
−7/2의 실수 값과 바닥 정수 값을 구하세요. 소수 부분을 0 방향으로 없애면 같은가요?
Find −7/2 and its floor. Is truncating toward zero equivalent?
풀이와 확인할 이유Solution and explanation
실수 값은 −3.5이고 바닥은 −4입니다. 0 방향으로 자르면 −3이므로 다릅니다. 음수 구간 번호를 계산할 때 바닥과 절단을 혼동하지 않습니다.
The quotient is −3.5 and floor −4. Truncating toward zero gives −3, which differs. This matters for negative-bin indices.
12. 변환 실패의 두 동작Two conversion-failure behaviors
이 장의 실제 실행에서 Python float("three")와 R as.numeric("three")는 각각 어떻게 기록되나요? R의 결과를 원래 관측된 수치라고 불러도 되나요?
How do the archived Python float("three") and R as.numeric("three") runs behave? Is the R result an originally observed number?
풀이와 확인할 이유Solution and explanation
Python은 ValueError, R은 경고와 NA를 기록합니다. R의 NA는 변환 실패로 생긴 표식이며 원문에 실제 수치가 관측되었다는 뜻이 아닙니다. 실패 이유와 원문을 보존합니다.
Python records ValueError; R records a warning and NA. The marker arose from failed conversion, not an observed numeric measurement. Retain the source text and failure reason.
13. 같은 곱셈 기호의 다른 결과The same multiplication symbol, different results
Python 기본 리스트 [1,2,3]*2와 R 수치 벡터 c(1,2,3)*2의 값과 길이를 비교하세요.
Compare values and lengths for Python basic list [1,2,3]*2 and R numeric vector c(1,2,3)*2.
풀이와 확인할 이유Solution and explanation
Python은 [1,2,3,1,2,3]으로 길이 6, R은 2,4,6으로 길이 3입니다. Python에서 각 값을 두 배로 하려면 이 장에서는 [x*2 for x in values]를 씁니다. NumPy 배열의 규칙과 기본 리스트를 구별합니다.
Python repeats six elements; R doubles three elements to 2, 4, 6. The explicit Python mapping is [x*2 for x in values]. Basic lists and NumPy arrays differ.
14. 혼합 벡터와 리스트A mixed atomic vector and a list
R에서 c(1,"2",TRUE)와 list(1,"2",TRUE)의 원소 자료형 보존은 어떻게 다른가요?
How do R c(1,"2",TRUE) and list(1,"2",TRUE) differ in preserving component types?
풀이와 확인할 이유Solution and explanation
원자 벡터 c는 공통 character로 변환됩니다. list는 각 성분의 double·character·logical 종류를 따로 보존할 수 있습니다. 변환 결과의 종류가 원필드의 측정 의미를 자동으로 정하지는 않습니다.
The atomic vector coerces to common character. The list retains separately typed double, character and logical components. Representation does not automatically establish field meaning.
15. 조건과 선택값A mask and its selected values
10,20,30,40에서 값≥25의 마스크와 선택된 값을 쓰세요. 마스크 원소의 종류와 선택값의 종류는 같은가요?
For 10, 20, 30, 40, write the mask for value≥25 and the selected values. Are their element types identical?
풀이와 확인할 이유Solution and explanation
마스크는 거짓,거짓,참,참이며 선택값은 30,40입니다. 앞은 논리값, 뒤는 수치값입니다. 마스크가 원자료의 어떤 위치와 대응하는지 확인해야 합니다.
The mask is false, false, true, true; selected values are thirty and forty. Logical conditions differ from selected numeric measurements.
16. 세 장바구니의 길이Lengths of three baskets
빈 묶음, 값 0 하나, 미관측 원소 하나의 길이를 각각 구하세요. 빈 합이 0이면 빈 평균도 관측값 0인가요?
Give lengths for an empty collection, one zero and one missing element. If an empty sum is zero, is the empty mean an observed zero?
풀이와 확인할 이유Solution and explanation
길이는 0,1,1입니다. 빈 합 0이라는 규약은 빈 평균에 관측값 0을 부여하지 않습니다. 평균의 유효 분모가 0이므로 별도 미정의·미관측 반환 규칙을 명시해야 합니다.
The lengths are zero, one and one. The empty-sum convention does not create an observed mean. A zero valid denominator needs an explicit undefined/missing return policy.
17. 보이는 0.3과 같음 비교A displayed 0.3 and equality
0.1+0.2가 화면에 0.3으로 반올림되어 보입니다. 따로 저장된 0.3과 정확한 같음 비교가 참이라고 결론내려도 되나요?
A screen rounds 0.1+0.2 to 0.3. Must exact equality with independently stored 0.3 be true?
풀이와 확인할 이유Solution and explanation
아닙니다. 출력 반올림과 저장된 이진 값은 다릅니다. 이 장의 긴 출력과 == 비교 기록으로 실제 차이를 확인할 수 있습니다. 근사 비교를 쓰려면 문제의 단위와 규모에 맞는 허용오차 근거가 필요합니다.
No. Display rounding differs from the stored binary value. Inspect the archived long output and equality result. Approximate comparisons require a tolerance justified by units and scale.
18. 실행 기록과 실시간 실행Recorded versus live execution
브라우저가 저장된 Python/R 출력과 코드 해시를 보여 줍니다. 임의로 고친 코드가 이 브라우저에서 실제 두 언어로 실행되었다고 말할 수 있나요?
A browser shows saved Python/R output and a code hash. Has an arbitrarily edited program thereby executed in those languages inside this browser?
풀이와 확인할 이유Solution and explanation
아닙니다. 이 장의 추적기는 고정 카탈로그에서 실제 과거 실행 기록을 선택합니다. 새 코드는 내려받은 파일을 실제 언어 런타임에서 실행해야 합니다. 해시는 파일 식별에 도움을 주지만 코드 의미의 타당성을 증명하지 않습니다.
No. The trace selects a fixed catalog of actual recorded runs. New code must run in a real runtime. Hashes identify content, not analytical validity.
19. 첫 위치와 원행 번호First position versus source-row key
가정 벡터 10,20,30에서 첫 값을 고르는 Python과 R 코드를 쓰세요. 선택 위치와 파일에 보관한 source_row_id가 항상 같다고 볼 수 있나요?
Write Python and R expressions selecting the first of 10, 20, 30. Must its current position equal its retained source_row_id?
풀이와 확인할 이유Solution and explanation
Python은 values[0], R은 values[1]입니다. 둘 다 값 10을 고릅니다. 현재 위치는 정렬·필터 뒤 바뀔 수 있지만 원행 키는 출처를 추적하려고 보관한 별도 필드입니다. 현재 첫 위치가 원파일의 첫 행임을 가정하지 않습니다.
Use Python values[0] and R values[1]; both select ten. Sorting and filtering can change current position. A retained source-row key is a separate provenance field, not automatically the current index.
20. 구간의 오른쪽 끝The right endpoint of a slice
Python의 [10,20,30,40][0:2]와 R의 c(10,20,30,40)[1:2]를 비교하세요. Python [2:2]와 R [2:2]도 같나요?
Compare Python [10,20,30,40][0:2] and R c(10,20,30,40)[1:2]. Are the two languages’ [2:2] selections equivalent?
풀이와 확인할 이유Solution and explanation
첫 두 식은 모두 10,20을 고릅니다. Python 슬라이스는 시작을 포함하고 끝을 제외하므로 2:2는 빈 리스트입니다. R의 2:2는 위치 2 하나를 만들므로 값 20입니다. 겉모양이 같은 기호만 번역하지 말고 위치 목록을 먼저 써 봅니다.
The first pair selects ten and twenty. Python excludes the stop position, so 2:2 is empty. R 2:2 supplies index two once, selecting twenty. Translate the intended position set rather than just the symbols.
21. 음수 인덱스의 두 뜻Two meanings of a negative index
세 값 10,20,30에서 Python values[-1]과 R values[-1]의 결과를 쓰세요. R에서 마지막 값을 하나 고르는 식도 제시하세요.
For 10, 20, 30, compare Python and R values[-1]. Give an R expression selecting just the last value.
풀이와 확인할 이유Solution and explanation
Python은 마지막 값 30, R은 첫 위치를 제외한 20,30입니다. R에서는 values[length(values)]로 마지막 위치를 고를 수 있습니다. 이 식은 비어 있지 않은 벡터를 전제로 했으며 빈 입력은 따로 검사해야 합니다.
Python selects thirty; R excludes the first position and retains twenty and thirty. For a nonempty R vector use values[length(values)]. Empty input needs a separate policy.
22. 범위 밖의 값은 어디에서 생겼나Where did an out-of-range marker originate?
길이 3의 기본 리스트·벡터에서 Python values[3]과 R values[4]를 실행했습니다. 둘 다 원자료에 네 번째 결측 관측이 있었다는 뜻인가요?
For a length-three basic list/vector, run Python values[3] and R values[4]. Did the source contain a fourth missing observation?
풀이와 확인할 이유Solution and explanation
아닙니다. 이 장의 Python 실행은 IndexError, R 실행은 범위 밖 선택으로 생긴 NA입니다. 원자료의 관측 개수는 여전히 세 개입니다. R이 만든 표식의 원인은 선택 오류이며, 원자료 파일에 있던 빈 칸과 구별해야 합니다.
No. The archived Python run raises IndexError; R creates NA for an out-of-range positive position. The source still has three elements. A marker created by invalid selection differs from a blank field already present in the source.
23. 값과 키에 같은 마스크를 적용한다Apply the same mask to values and keys
원행 키는 11,25,42이고 대응 값은 2,8,4입니다. 값≥4를 선택한 뒤 키를 원래 첫 두 개 11,25로 붙이면 왜 틀리나요? 올바른 두 쌍을 쓰세요.
Keys 11, 25, 42 correspond to values 2, 8, 4. Select values≥4. Why is attaching the original first two keys wrong? Give the correct pairs.
풀이와 확인할 이유Solution and explanation
조건 마스크는 거짓,참,참입니다. 키와 값에 같은 마스크를 적용해야 (25,8),(42,4)를 얻습니다. 값만 줄이고 키를 앞에서 잘라 붙이면 출처가 어긋납니다. 실제 파일에서는 행 전체를 함께 선택하는 방법도 쓸 수 있습니다.
The mask is false, true, true. Apply it to both fields, giving (25,8) and (42,4). Taking the first two keys instead misidentifies the selected records. Selecting whole rows together is another way to preserve alignment.
24. 반복문의 중간 상태Intermediate loop states
total=0에서 시작해 값 2,4,6을 차례로 더합니다. 각 반복 뒤 total과 마지막 total을 3으로 나눈 값을 쓰세요. 처음부터 모든 원소가 4가 된다는 뜻인가요?
Starting total at zero, add 2, 4, 6 in order. List the running totals and final total divided by three. Have all original elements become four?
풀이와 확인할 이유Solution and explanation
중간 합은 2,6,12이고 평균은 12/3=4입니다. 4는 전체 요약값이며 원소 2,4,6을 바꾸지 않습니다. 각 반복에서 현재 값과 누적 합을 함께 적으면 합계를 두 번 더하는 실수나 초기화 위치 오류를 찾기 쉽습니다.
Running totals are two, six and twelve; the mean is four. A summary does not replace the original elements. Recording the current element and running total helps detect duplicate additions and misplaced initialization.
25. 빈 R 반복 범위An empty R loop range
R에서 빈 벡터의 길이는 0입니다. 위치를 만들 때 1:length(values)와 seq_along(values)가 어떻게 다른가요?
An R vector has length zero. Compare 1:length(values) and seq_along(values) as position sequences.
풀이와 확인할 이유Solution and explanation
앞 식은 1:0, 즉 1과 0 두 위치를 만듭니다. 뒤 식은 길이 0의 정수 벡터를 만듭니다. 모든 실제 위치를 차례로 방문하려는 반복에는 seq_along이 빈 입력에서도 의도와 맞습니다. 이것으로 빈 평균의 값이 정의되는 것은 아니므로 반환 규칙은 따로 필요합니다.
The former produces 1:0, namely positions one and zero. The latter produces an empty integer vector. For iterating over existing positions, seq_along preserves the intended empty case. An empty-mean return policy is still a separate decision.
26. 공개 코드 407의 두 원행Two source rows carrying public code 407
실제 NJ/PA 파일의 코드 407은 원행 42와 168에 나타납니다. 첫 기록의 FTE는 11→11, 둘째는 12→14.5입니다. 코드만 키로 삼아 한 행을 지워도 되나요? 각 변화도 구하세요.
Actual code 407 occurs at original rows 42 and 168. Their FTE values are 11→11 and 12→14.5. May one be removed using code alone? Calculate each change.
풀이와 확인할 이유Solution and explanation
원행별 변화는 0과 2.5 FTE입니다. 같은 코드라는 이유만으로 같은 관측의 복제라고 결론낼 수 없습니다. 원행 42는 PA·체인 2,168은 NJ·체인 4로 구별됩니다. 이 장은 두 출처 행을 모두 보존하며 코드와 원행 키를 함께 보여 줍니다. 두 행만의 평균을 전체 384쌍 평균으로 읽지 않습니다.
The changes are zero and 2.5 FTE. Equal public codes alone do not establish duplicate observations. Row 42 is PA/chain 2; row 168 is NJ/chain 4. Retain both source rows and show code with source-row key. These two examples do not determine the full 384-pair mean.
27. 함수 호출의 입력과 반환Function input and returned value
average(values)가 합/길이를 반환하고 입력은 2,4,6입니다. 인자,합,분모,반환값을 각각 쓰세요. 함수를 정의만 하고 호출하지 않으면 answer가 만들어지나요?
A function average(values) returns sum divided by length for input 2, 4, 6. Identify argument, sum, denominator and return. Does merely defining it create answer?
풀이와 확인할 이유Solution and explanation
인자는 세 값의 묶음,합은 12,분모는 3,반환값은 4입니다. 함수 정의는 계산 절차를 이름에 연결합니다. 호출 뒤 answer = average(rows) 또는 R의 대응 할당을 실행해야 answer가 생깁니다. 함수 이름과 계산 결과 이름은 별개입니다.
The argument contains three values, its sum is twelve, denominator three and return four. A definition binds a procedure. Call it and assign its return to answer; the function name and result name are distinct bindings.
28. 출력만 하는 함수의 함정A function that only displays output
Python 함수가 print(4)만 실행하고, R 함수가 cat(4)를 마지막으로 실행합니다. 두 함수의 결과를 answer에 넣었을 때 화면과 반환값을 구별하세요.
A Python function only executes print(4); an R function ends with cat(4). If each call is assigned to answer, distinguish displayed output from return.
풀이와 확인할 이유Solution and explanation
화면에는 4가 나타나지만 Python의 암묵 반환은 None,이 R 함수의 반환은 NULL입니다. 따라서 answer에 수치 4가 저장되었다고 볼 수 없습니다. 실제 반환값이 필요한 함수는 명시한 수치 값을 return하도록 만듭니다. R의 print는 값을 보이지 않게 반환할 수 있으므로 모든 출력 함수를 cat과 동일시하지 않습니다.
Four appears on screen, but the Python implicit return is None and this R cat call returns NULL. Answer therefore does not hold numeric four. Explicitly return a numerical value when needed. R print can invisibly return its argument, so do not generalize cat’s behavior to every display function.
29. 마지막 식과 명시 반환Last expression and explicit return
Python 함수 본문이 x * 2라는 식으로만 끝나고 R 함수도 마지막 식이 x * 2입니다. x=3에서 반환은 각각 무엇인가요? 두 언어에서 명확하게 6을 반환하는 방법도 설명하세요.
A Python function ends with only the expression x*2; an R function also ends with x*2. For x=3, compare returns and make the return of six explicit.
풀이와 확인할 이유Solution and explanation
Python은 return이 없어 None,R은 마지막 식의 값 6을 반환합니다. Python에는 return x * 2, R에는 return(x * 2)를 쓸 수 있습니다. 이 차이는 실제 실행 기록으로 확인합니다. 화면에 자동으로 보였는지와 호출자가 받은 값은 구별합니다.
Python returns None without return; R returns the last expression’s six. Write Python return x * 2 and R return(x * 2). Whether a console automatically displays a value is distinct from what the caller receives.
30. 함수 안팎의 같은 이름The same name inside and outside a function
밖의 x=100이고 이 장의 함수 안에서는 지역 x=3을 만든 뒤 x+1을 반환합니다. 호출 결과와 밖의 x를 쓰세요. 이 예제로 함수가 외부 상태를 절대로 바꾸지 않는다고 증명했나요?
Outer x=100. This chapter’s function creates local x=3 and returns x+1. Give the return and outer x. Does this prove that functions can never change external state?
풀이와 확인할 이유Solution and explanation
호출 결과는 4,밖의 x는 100입니다. 이 예제의 지역 이름과 외부 이름이 다른 연결이라는 뜻입니다. 모든 함수가 외부 객체를 바꾸지 않는다는 증명은 아닙니다. 이 장의 작은 함수는 입력과 반환에 집중하지만 부작용이 가능한 다른 코드에서는 별도 검토가 필요합니다.
The return is four and outer x remains one hundred. It demonstrates local bindings in this example, not a universal absence of side effects. Other code can require a separate examination of external mutation.
31. 이름 붙인 인자와 단위Named arguments and units
함수 affine(value,scale=1,shift=0)가 value×scale+shift를 반환합니다. 섭씨 20을 화씨로 바꾸는 인자와 답을 쓰세요. 인자 이름만으로 실제 입력의 단위가 검사되나요?
affine(value,scale=1,shift=0) returns value×scale+shift. Supply arguments converting 20°C to Fahrenheit. Do argument names alone verify input units?
풀이와 확인할 이유Solution and explanation
value=20,scale=9/5,shift=32로 68°F입니다. 기본값을 쓰면 20으로 남으므로 호출 때 올바른 변환을 지정해야 합니다. 함수가 단순 수치만 받는다면 섭씨인지 다른 단위인지 자동 검증하지 않습니다. 자료 사전·함수 계약·출력 단위를 함께 적습니다.
Use value=20, scale=9/5 and shift=32, returning 68°F. Defaults would leave twenty unchanged. A purely numeric function does not automatically know the input unit; retain the dictionary, contract and output units.
32. 빈 입력을 위한 두 줄Two branches for an empty input
평균 함수가 입력 길이 0을 만나면 Python None/R NA_real_을 반환하고,그 외에는 합/길이를 반환하도록 설계했습니다. 빈 입력과 0 하나에서 어떤 답이 나와야 하나요?
A mean function returns Python None/R NA_real_ when length is zero, otherwise sum/length. What should empty input and a singleton zero return?
풀이와 확인할 이유Solution and explanation
빈 입력은 정한 미정의 표식,0 하나는 관측 평균 0입니다. 길이를 먼저 검사하면 Python의 0/0 오류나 R의 빈 평균 NaN을 그대로 퍼뜨리는 대신 함수 계약을 명확하게 구현합니다. 이것은 원자료의 미관측 원인까지 알아냈다는 뜻이 아닙니다.
Empty input returns the specified undefined marker; the observed zero returns numeric zero. A length guard implements a clear contract instead of propagating division-by-zero or empty-mean behavior. It does not identify the original cause of unavailable data.
33. 변환·범위·의미의 세 검사Conversion, range and meaning
"20"은 수로 바꿀 수 있고 "three"는 이 예제에서 바꿀 수 없습니다. 그런데 점포 코드 "407"도 수로 바꿀 수 있습니다. 수치 분석에 쓸 필드를 정하려면 무엇을 더 확인해야 하나요?
Text "20" converts numerically while "three" fails in this example. Store code "407" also converts. What else is needed before using a field numerically?
풀이와 확인할 이유Solution and explanation
변환 가능성 뒤에도 허용 범위·유한성·단위·관측 의미를 확인해야 합니다. 예를 들어 온도 20과 식별자 407은 산술의 의미가 다릅니다. 실패한 원문은 보관하고,변환 성공만으로 임금·몸무게처럼 연속 측정값이라고 부르지 않습니다.
Inspect allowed range, finiteness, units and measurement meaning after conversion. Temperature twenty and identifier 407 have different arithmetic interpretations. Preserve failed source text; conversion success does not establish a continuous measurement.
34. 요약 함수의 계약을 직접 쓴다Write the summary function’s contract
Python 함수가 None만 제외하고 R 함수가 is.na인 원소를 제외한다고 합시다. [2,미관측,4]를 두 언어가 요약할 때 같아지는 조건과,NaN·Inf까지 자동 해결했다고 말할 수 없는 이유를 설명하세요.
Python excludes only None; R excludes values satisfying is.na. Under what input conditions do they agree on [2,missing,4]? Why have NaN and Inf not automatically been handled?
풀이와 확인할 이유Solution and explanation
유한한 수치 또는 합의한 미관측 표식만 있다는 입력 조건에서 유효 2개·합 6·평균 3으로 맞출 수 있습니다. Python의 None 검사만으로 NaN을 제외하지 않으며 R의 is.na는 Inf를 제외하지 않습니다. 실제 분석에서 NaN·Inf가 가능하면 별도 검사와 정책을 계약에 추가하고 검증해야 합니다.
With only finite numerical values and the agreed missing markers, both retain two values, sum six and mean three. None-only filtering does not remove Python NaN, and R is.na does not remove Inf. Add and verify a separate policy when nonfinite inputs are possible.
35. 관측 0을 버리지 않는다Retain observed zero
자료 2,미관측,4,0의 가용 평균을 구하세요. 모든 원소의 참·거짓만 보고 거짓인 값을 버리는 방법은 왜 위험한가요?
Find the available mean of 2, missing, 4, 0. Why is filtering solely by each element’s truth value unsafe?
풀이와 확인할 이유Solution and explanation
가용값은 2,4,0 세 개이므로 6/3=2입니다. 관측 0도 거짓처럼 평가될 수 있어 단순한 truthiness 필터는 유효값을 잘못 버립니다. 미관측 표식을 명시적으로 검사하고 원래 0이 관측되었다는 사실을 보존해야 합니다.
Retain two, four and zero, giving 6/3=2. An observed zero can evaluate as false, so a truthiness filter can wrongly discard valid data. Test the specified missing marker explicitly.
36. 모두 미관측인 두 기록Two entirely unavailable records
원래 두 행이 있으나 두 값이 모두 미관측입니다. 원행 수·유효 수·유효 합·가용 평균을 각각 보고하세요. 유효 합이 0이면 그래프에 평균 0 막대를 그려도 되나요?
Two source rows both have missing values. Report source count, valid count, valid sum and available mean. Does a zero valid sum justify a mean-zero bar?
풀이와 확인할 이유Solution and explanation
원행 수 2,유효 수 0,빈 합 규약의 유효 합 0,가용 평균은 미정의입니다. 0이라는 합은 관측값이 모두 0이었다는 뜻이 아닙니다. 평균 그래프에는 수치 막대를 만들지 말고 가용값 없음과 분모 0을 설명합니다.
Counts are two and zero; the empty-sum convention gives sum zero, but the mean is undefined. This is not evidence that observed values were all zero. Display an unavailable-mean message rather than a numerical mean bar.
37. NaN과 NA를 같음으로 찾지 않는다Do not find NaN/NA using equality
Python NaN==NaN은 거짓이고 R NA==NA는 NA입니다. 이것으로 결측 탐지가 불가능하다고 결론낼 수 있나요? 이 장의 두 언어 검사 함수를 제시하세요.
Python NaN==NaN is false, while R NA==NA is NA. Is missingness therefore undetectable? Give the relevant checks.
풀이와 확인할 이유Solution and explanation
같음 비교가 표식 탐지 도구가 아니라는 뜻입니다. Python의 수치 NaN에는 math.isnan,None에는 is None을 씁니다. R은 is.na로 NA와 NaN을 검사하고 is.nan으로 NaN을 구별할 수 있습니다. Python의 isnan에 임의 객체를 그대로 넣지 않도록 입력 자료형을 확인합니다.
Equality is not the appropriate marker test. Use Python math.isnan for numerical NaN and is None for None. R is.na detects NA and NaN, while is.nan distinguishes NaN. Check input types before passing arbitrary objects to Python isnan.
38. NULL·NA·빈 벡터NULL, NA and an empty vector
R의 NULL,NA_real_,numeric(0)의 길이와 의미를 비교하세요. 길이가 같은 두 객체는 자료형과 용도도 반드시 같나요?
Compare R NULL, NA_real_ and numeric(0) by length and meaning. Do equal lengths guarantee identical types and purposes?
풀이와 확인할 이유Solution and explanation
길이는 각각 0,1,0입니다. NA_real_은 미관측 수치 원소 하나,numeric(0)은 원소 없는 수치 벡터,NULL은 별도의 빈 객체입니다. 길이 0이라는 공통점만으로 NULL과 numeric(0)의 자료형·함수 동작이 같다고 결론낼 수 없습니다.
Lengths are zero, one and zero. NA_real_ is one missing numeric element; numeric(0) is an empty numeric vector; NULL is a distinct empty object. Equal zero length does not establish identical types or behavior in every function.
39. None만 검사하면 NaN은 남는다A None-only filter retains NaN
Python 자료 [2.0,None,float("nan"),4.0]에 x is not None만 적용했습니다. 유효하다고 남은 원소 수와 평균 계산의 문제를 설명하세요.
Apply only x is not None to Python [2.0,None,float("nan"),4.0]. How many elements remain, and what happens to the mean?
풀이와 확인할 이유Solution and explanation
세 원소 2.0,NaN,4.0이 남습니다. 이들의 합과 평균은 NaN이므로 유한한 가용 평균 3을 얻지 못합니다. 유한 측정값의 평균이라는 목적이라면 수치 자료형과 math.isfinite를 확인하는 별도 정책이 필요합니다. 제외 전 원문과 이유는 유지합니다.
Three remain: 2.0, NaN and 4.0. Their sum and mean are NaN, not the finite mean three. A finite-measurement contract needs an additional numeric/finiteness policy, retaining excluded source values and reasons.
40. Inf는 R is.na로 제거되지 않는다R is.na does not remove Inf
R의 c(2,Inf,4)에 values[!is.na(values)]를 적용하면 Inf가 사라지나요? 원자료의 Inf를 이유 없이 0으로 바꾸는 것은 해결인가요?
Does values[!is.na(values)] remove Inf from c(2,Inf,4)? Is replacing an unexplained Inf by zero a solution?
풀이와 확인할 이유Solution and explanation
Inf는 is.na가 거짓이므로 남고 평균도 Inf입니다. 유한 측정값만을 요약하려면 is.finite 같은 추가 검사와 제외·오류 정책을 명시합니다. 원인이 수치 overflow인지 원문 표식인지 먼저 조사해야 하며 0 치환은 관측값과 분모를 바꾸므로 자동 해결이 아닙니다.
No: Inf remains and the mean is Inf. A finite-value summary requires an additional check such as is.finite and an explicit rejection/exclusion policy. Investigate numerical overflow versus a source marker; zero replacement changes data and the target calculation.
41. 미관측과 문턱 비교A threshold and missingness
자료 [2,미관측,4]에서 값<3인 가용 기록을 고릅니다. Python에서 None과 직접 비교하는 대신 어떤 순서로 조건을 확인해야 하나요? 결과는 무엇인가요?
Select available values<3 from [2,missing,4]. In Python, what check must precede comparison with three? What is selected?
풀이와 확인할 이유Solution and explanation
먼저 x is not None을 확인한 뒤 x < 3을 평가하도록 and의 단락 평가를 씁니다. 결과는 2 하나입니다. R에서는 먼저 가용 위치를 선택하고 그 값에 조건을 적용할 수 있습니다. 미관측을 문턱 아래 또는 위로 임의 분류하지 않습니다.
Use short-circuit and to check x is not None before x<3. The selected value is two. In R, filter available positions before applying the numeric condition. Missingness is not automatically below or above the threshold.
42. 네 가지 미관측 표식의 출처Four origins of unavailable output
원파일 빈 칸,문자 "three"의 수치 변환 실패,범위 밖 선택,가용 원소 0개의 평균이 모두 비슷한 빈 표시로 보입니다. 결과 열 하나만 남길 때 무엇을 잃나요?
A raw blank, failed conversion of "three", an out-of-range index and a zero-valid-count mean look similarly blank. What is lost by retaining only one result column?
풀이와 확인할 이유Solution and explanation
원래 관측되지 않은 값과 프로그램에서 새로 생긴 오류·미정의를 구별할 근거를 잃습니다. 원문,원행 키,변환·선택 단계,표식 원인,유효 분모를 보존합니다. 화면이 같아도 네 상황의 자료 수집·코드 수정·해석 대응은 다를 수 있습니다.
You lose the distinction between originally unavailable data and markers newly created by conversion, selection or an undefined calculation. Preserve source text/key, processing stage, reason and valid denominator; the appropriate remedy differs.
43. 가용 평균을 손으로 추적한다Trace an available mean by hand
None만 제외하는 작은 함수에 [2,None,4,0]을 넣습니다. valid 목록,합,길이,반환을 쓰고,None까지 0으로 채워 네 개로 나눈 값과 비교하세요.
Trace a None-only filter on [2,None,4,0]: valid list, sum, length and return. Compare replacing None with zero and dividing by four.
풀이와 확인할 이유Solution and explanation
valid=[2,4,0],합 6,길이 3,반환 2입니다. 0 채움 후 평균은 6/4=1.5입니다. 두 계산은 분모와 원소 의미가 다릅니다. 후자는 원 미관측이 0이었다는 별도 가정이며,이 장의 가용 평균과 동일한 처리라고 부르지 않습니다.
Valid=[2,4,0], sum six, length three and return two. Zero filling gives 6/4=1.5. It changes the denominator and asserts a numerical value for an unavailable record, unlike the available-value summary.
44. 작은 검사 세 개Three small checks
가용 평균 함수의 계약은 유한 수치·미관측 표식이며 빈 유효 집합은 Python None/R NA_real_입니다. 2,4,6과 0,4와 모두 미관측인 입력의 예상 결과를 이용해 검사 계획을 쓰세요.
The contract accepts finite numbers and agreed missing markers, returning Python None/R NA_real_ for no valid values. Design checks using 2,4,6; 0,4; and all-missing input.
풀이와 확인할 이유Solution and explanation
세 예상 결과는 4,2,미정의 표식입니다. 앞 두 개는 수치 같음으로,마지막은 Python의 is None/R의 is.na로 확인할 수 있습니다. 실패하면 합·유효 수·반환 분기를 나누어 조사합니다. 세 검사를 통과한 것만으로 모든 객체나 인과 해석의 타당성을 인증하지 않습니다.
Expected returns are four, two and the specified undefined marker. Check numerical equality for the first two and is None/is.na for the third. Inspect sum, valid count and branch on failure. Passing three cases does not certify every object or causal interpretation.
45. 실제 GDP 단위 변환Convert the actual GDP-per-person unit
실제 호주의 2024년 1인당 실질 GDP는 61,486.38147544(2015년 USD/인)입니다. 1만 USD/인 단위로 바꾸면 얼마인가요? 국가 총 GDP로 바뀐 건가요?
Australia’s actual 2024 real GDP per capita is 61,486.38147544 in 2015 USD/person. Express it in units of 10,000 USD/person. Has it become total GDP?
풀이와 확인할 이유Solution and explanation
10,000으로 나눠 6.148638147544(1만 2015년 USD/인)입니다. 표시 단위를 바꾼 것이며 여전히 1인당 지표입니다. 인구를 곱하지 않았으므로 국가 총액으로 바뀌지 않았습니다. 코드·표·그래프의 단위를 함께 고칩니다.
Divide by 10,000 to get 6.148638147544 in ten-thousand 2015 USD/person. Only the display unit changed; it remains a per-person indicator. No population multiplication created a national total. Update code, table and graph units together.
46. 실제 수치 목록을 두 배로 하는 코드Transform each actual numeric value
Python에서 GDP 값 두 개가 담긴 기본 리스트 values에 values * 2를 실행했습니다. 국가 수를 바꾸지 않고 각 값의 단위 변환을 하려던 목적과 맞나요? 각 값을 10,000으로 나누는 코드를 쓰세요.
Python values is a basic list containing two GDP measurements. Does values*2 perform a per-value unit transformation? Write code dividing each value by 10,000.
풀이와 확인할 이유Solution and explanation
기본 리스트 곱은 두 원소를 두 번 반복해 길이 4를 만듭니다. 단위 변환에는 [x / 10000 for x in values]를 씁니다. R의 수치 벡터는 values / 10000으로 원소별 계산을 합니다. 변환 뒤에도 원 국가 키 두 개와 값 두 개의 대응을 유지합니다.
List multiplication repeats both entries and creates length four. Use [x / 10000 for x in values] for mapping. For an R numeric vector use values / 10000. Retain the two original country keys aligned with their two transformed values.
47. 실제 Card의 두 분모Two denominators in the actual Card file
실제 사람 원행 3,613개 중 가용 로그 임금 3,010개와 미관측 603개가 있습니다. 가용 평균의 분모와 모든 원행을 분모로 하는 0 채움 평균이 어떻게 다른지 설명하세요.
Among 3,613 actual source rows, 3,010 log wages are available and 603 unavailable. Compare the available-mean denominator with zero filling all rows.
풀이와 확인할 이유Solution and explanation
가용 평균은 가용 로그 합/3,010입니다. 0 채움 평균은 같은 합/3,613이므로 가용 평균 6.261831917744에 3,010/3,613을 곱한 다른 값이 됩니다. 관측이 없는 로그를 실제 0으로 바꾸는 가정과 전체 대상 평균의 식별은 별개입니다. 603개 원행을 지우거나 실제 임금 0으로 부르지 않습니다.
The available mean is the available log sum/3,010. Zero filling divides the same sum by 3,613, multiplying 6.261831917744 by 3,010/3,613. Assigning log zero is an additional assumption; it does not identify the all-person mean. Preserve the 603 source rows.
48. 로그 평균을 통화 평균으로 읽지 않는다A log mean is not a currency mean
실제 Card의 가용 로그 임금 평균이 약 6.261831918입니다. 이것을 6.26달러/시간이라고 읽어도 되나요? 원변수와 변환 단계를 설명하세요.
The available Card log-wage mean is about 6.261831918. Is this 6.26 dollars/hour? Explain the source variable and transformation.
풀이와 확인할 이유Solution and explanation
아닙니다. 원 로그는 1976년 시간당 센트 임금의 원자료 극단값 정리 변수입니다. 로그 평균 자체는 달러/시간의 산술평균이 아닙니다. 평균을 지수화한 값과 개별 임금을 지수화해 평균한 값도 일반적으로 다릅니다. 통화 단위 전환에 필요한 100으로 나눔과 자료 정의를 별도로 설명해야 합니다.
No. The source is the extreme-value-trimmed log of 1976 hourly wages measured in cents. A log mean is not an arithmetic dollar/hour mean. Exponentiating the mean differs generally from averaging individually exponentiated wages. Currency conversion by 100 and the source definition require separate explanation.
49. 실제 FTE 함수의 한 줄One line of the FTE function
점포의 정규직 8명,시간제 10명,관리자 2명일 때 자료 사전의 FTE=정규직+0.5×시간제+관리자로 값을 구하세요. 시간제 수가 미관측이면 자동 0으로 두나요?
A store has eight full-time, ten part-time and two managers. Use FTE=full-time+0.5×part-time+managers. What if part-time count is unavailable?
풀이와 확인할 이유Solution and explanation
FTE=8+5+2=15입니다. 시간제 수가 미관측이면 이 장의 완전 성분 규칙에서는 해당 시점 FTE도 미관측입니다. 0명이라는 관측과 정보 없음은 다릅니다. 부분 합을 구할 수 있어도 이를 완전한 FTE로 바꾸어 부르지 않습니다.
FTE is 8+5+2=15. Under this chapter’s complete-component rule, unavailable part-time count makes the wave’s FTE unavailable. A partial sum is not the complete measure, and unavailable does not mean observed zero employees.
50. 짝 변화의 분모The denominator for paired changes
실제 점포 410행에서 두 시점 FTE가 모두 있는 384쌍의 변화 평균을 구합니다. 분모를 410으로 하고 나머지 26개 변화를 0으로 두면 같은가요? 전체 평균 −541/7680의 단위도 쓰세요.
Of 410 actual store rows, 384 have both-wave FTE. Is replacing the other 26 changes by zero and dividing by 410 equivalent? State the unit of −541/7680.
풀이와 확인할 이유Solution and explanation
같지 않습니다. 완전짝 변화 합을 384로 나눈 값이 −541/7680≈−0.0704427083 FTE입니다. 410으로 나누려면 나머지 변화가 0이라는 추가 가정을 넣은 셈입니다. 미관측 26개는 보존하고 완전짝에 대한 기술값과 모든 점포의 변화·정책 효과를 구별합니다.
No. The complete-pair change sum divided by 384 is −541/7680≈−0.0704427083 FTE. Dividing by 410 with the same numerator assumes zero missing changes. Preserve those 26 rows and distinguish the complete-pair description from all-store change or a policy effect.
51. 정렬 뒤 원행 키Source-row keys after sorting
원행 키 42의 FTE 변화는 0이고 168의 변화는 2.5 FTE입니다. 두 기록을 변화 내림차순으로 정렬합니다. 현재 첫 위치와 첫 기록의 원행 키는 무엇인가요? 원행 키를 1,2로 덮어쓰면 무엇을 잃나요?
Source row 42 has FTE change zero; source row 168 has change 2.5 FTE. Sort these records by descending change. Give current first position and its source-row key. What is lost by overwriting keys with one and two?
풀이와 확인할 이유Solution and explanation
변화 2.5인 원행 168이 먼저 오고,변화 0인 원행 42가 뒤에 옵니다. 현재 첫 위치는 Python 0/R 1이지만 원행 키는 168입니다. 원행 키를 새 순번으로 덮어쓰면 원파일의 출처 추적이 어려워집니다. 필요하면 현재 순번을 별도 필드로 추가합니다.
Row 168 with change 2.5 comes before row 42 with change zero. Its current first position is Python zero/R one, while its source-row key remains 168. Keep any new display rank separate from provenance keys.
52. 두 언어의 마지막 자릿수Different final displayed digits
같은 유한 수치 파일을 Python과 R이 읽고 가용 분모도 맞췄는데 평균의 마지막 표시 자릿수가 조금 다릅니다. 곧바로 두 언어가 다른 모집단을 분석했다고 결론낼 수 있나요?
Python and R read the same finite numeric file and use the same valid denominator, but their last displayed mean digit differs. Must they have analyzed different populations?
풀이와 확인할 이유Solution and explanation
아닙니다. 먼저 입력 파일 해시·선택 원행·변환 규칙·분모·단위가 같은지 확인합니다. 그 다음 합산 순서,이진 저장,출력 반올림을 조사합니다. 의미와 입력 차이를 먼저 배제한 뒤 문제의 규모에 맞는 수치 허용오차를 정합니다. 화면에 같은 소수로 보인다는 사실만으로 코드와 입력이 동일함을 증명할 수도 없습니다.
No. First verify file hash, selected source rows, conversion, denominator and units. Then inspect summation order, binary representation and display rounding. Justified numerical tolerance follows those checks. Identical rounded output alone likewise does not prove identical inputs or code.
53. 해시가 증명하는 것What a hash establishes
코드 SHA-256과 입력 SHA-256이 보관 기록과 같습니다. 이 사실이 원자료의 측정 정확성이나 인과 해석의 타당성까지 증명하나요?
Code and input SHA-256 match an archived run. Does this certify measurement accuracy or causal validity?
풀이와 확인할 이유Solution and explanation
해시는 바이트 내용의 동일성을 확인하는 강한 실무 근거이지 분석 의미의 인증서가 아닙니다. 같은 잘못된 코드를 같은 잘못된 입력에 반복 적용할 수도 있습니다. 출처·자료 사전·관측 단위·처리 계약·실제 실행과 과학적 가정을 각각 확인합니다.
A hash supplies practical evidence of byte-content identity, not an analytical certificate. The same incorrect code can repeatedly process the same unsuitable input. Separately examine provenance, dictionary, observation units, processing contract, execution and scientific assumptions.
54. 셀 순서를 고치는 방법Repairing a cell order
셀3을 처음 실행하면 함수나 rows가 없어 오류가 났지만,셀1·2를 실행한 뒤 셀3이 성공했습니다. 오류 문구만 숨기는 방법과 새 프로세스에서 1→2→3을 실행하는 방법의 차이를 설명하세요.
Cell 3 initially fails because rows or the function is absent, then succeeds after cells 1 and 2. Compare hiding the message with running 1→2→3 in a fresh process.
풀이와 확인할 이유Solution and explanation
숨기기는 필요한 이름을 만들지 않으며 계산의 의존성을 해결하지 않습니다. 새 프로세스에서 입력 생성→함수 정의→호출을 순서대로 실행하면 이 예제의 의존성을 명시할 수 있습니다. 오류를 잡고 계속하는 기록기에서는 나중 성공도 가능하지만 앞선 실패 이력을 지우지 않습니다.
Hiding a message does not create required bindings. Input creation, definition and call in dependency order make this example reproducible. A recorder may catch an earlier failure and later succeed, but it should retain the failure history.
55. 새 프로세스의 이름 오류An absent name in a fresh process
어제 만든 rows가 오늘 새 프로세스에는 없습니다. average(rows)만 실행할 때 생기는 문제는 평균 공식의 반례인가요? 재현 파일에 무엇을 포함해야 하나요?
Yesterday’s rows is absent today. Does failure of average(rows) refute the mean formula? What belongs in a reproducible file?
풀이와 확인할 이유Solution and explanation
이름이 없다는 실행 환경 문제이며 평균 공식의 반례는 아닙니다. 필요한 입력 읽기·검사·함수 정의·호출을 파일에 포함하고 외부 파일 경로와 버전을 기록합니다. 새 프로세스에서 처음부터 실행해 우연히 남은 메모리에 의존하지 않는지 확인합니다.
It is a missing-binding problem, not a counterexample to the formula. Include input loading/checks, function definition and call, with paths and versions. Rerun from the beginning in a fresh process rather than depending on leftover memory.
56. 읽기·변환·요약을 나눈다Separate reading, conversion and summary
CSV의 원문 값은 "2","three","4"입니다. 세 행 읽기에는 성공했습니다. 수치 변환·요약까지 성공했다고 말할 수 있나요? 안전한 보고 순서를 제시하세요.
CSV fields are "2", "three", "4" and all three rows were read. Have numerical conversion and summary also succeeded? Give a transparent workflow.
풀이와 확인할 이유Solution and explanation
읽기 성공과 변환 성공은 별개입니다. 원행 세 개와 원문을 보관하고 "three"의 변환 실패를 원행 키와 함께 기록합니다. 유효 수치 두 개만 요약하기로 정했다면 합 6·분모 2·평균 3을 보고하며,이 제외 정책과 실패 이유를 함께 적습니다. 몰래 0으로 바꾸거나 행을 지우지 않습니다.
Reading success is separate from conversion success. Retain three source rows/text and record the failed conversion with its key. Under an explicit available-numeric policy, sum two valid numbers to six and divide by two to get three. Report the exclusion reason rather than silently zero filling or deleting.
57. R의 print와 cat을 한 규칙으로 외우지 않는다Do not memorize print and cat as one R rule
R에서 f <- function(x) print(x)와 g <- function(x) cat(x)를 만듭니다. x=4에서 반환과 출력의 차이를 설명하세요.
Compare R f<-function(x) print(x) and g<-function(x) cat(x), for x=4.
풀이와 확인할 이유Solution and explanation
둘 다 화면에 4를 보여 줄 수 있지만 print는 인자를 보이지 않게 반환하므로 f(4)를 할당하면 수치 4를 받을 수 있습니다. cat은 NULL을 반환하므로 g(4)를 할당하면 NULL입니다. 코드의 마지막 호출이 무엇을 반환하는지 실제로 확인해야 하며,출력은 언제나 NULL이라는 일반화는 틀립니다.
Both can display four. Print invisibly returns its argument, so assigning f(4) can retain numerical four. Cat returns NULL, so assigning g(4) retains NULL. Inspect the actual return of the final call; not every output operation returns NULL.
58. 긴 벡터 표시와 전체 계산Truncated display versus full computation
실제 3,613행을 읽은 기록 화면은 길어서 앞부분만 보여 줍니다. 화면에 보이는 열 개만으로 평균을 계산했다고 볼 수 있나요? 무엇을 확인해야 하나요?
The archived display truncates a long vector after reading 3,613 source rows. Was the mean computed from only the ten visible entries? What should be checked?
풀이와 확인할 이유Solution and explanation
표시가 잘렸는지 계산 입력도 잘렸는지를 구별해야 합니다. 이 장의 실제 요약 코드는 전체 파일을 읽고 3,010개 가용 로그로 평균을 계산하며,기록의 긴 객체 표현만 축약합니다. 코드의 선택 부분,원행 수,가용 분모,입력 해시를 확인하고 화면에 보이는 일부 행을 전체 표본으로 오해하지 않습니다.
Distinguish display truncation from truncation of analysis input. This chapter’s actual summary reads the full file and uses all 3,010 available logs; only long object representations are shortened. Check code, source count, valid denominator and input hash.
59. 검사 통과와 계약의 범위Passing checks and a contract’s scope
함수가 2,4,6과 빈 입력의 검사를 통과했습니다. 입력에 문자열·무한대·참거짓을 섞어도 항상 올바른 측정 평균을 반환한다고 말할 수 있나요?
A function passes tests on 2,4,6 and empty input. Does it always produce a valid measurement mean for strings, infinity and booleans too?
풀이와 확인할 이유Solution and explanation
아닙니다. 검사한 사례와 명시한 입력 계약 안에서만 근거가 생깁니다. 숫자처럼 산술에 참여할 수 있는 논리값도 측정값으로 허용할지는 별도 판단입니다. 허용 자료형·유한성·결측 표식·단위·원행 보존을 계약에 적고 필요한 반례를 추가합니다. 표본 검사를 모든 프로그램 입력에 대한 증명이라고 부르지 않습니다.
No. Evidence covers the tested cases and stated input contract. A logical value can participate in arithmetic without being an allowed measurement. Specify types, finiteness, markers, units and key preservation, then add relevant counterexamples. Finite testing is not a proof for every input.
60. 실제 파일의 재현 설명서Explain a fresh run on an actual file
국가·사람·점포 중 하나를 골라 내려받은 실제 코드를 새 프로세스에서 실행하세요. 코드를 외우지 않은 동료에게 입력부터 출력까지 설명할 일곱 항목과,이번 장에서 인증하지 않은 해석 한 가지를 제시하세요.
Choose country, person or store data and run its downloaded code in a fresh process. Give seven items a colleague needs to understand the full path from input to output, plus one interpretation not certified here.
풀이와 확인할 이유Solution and explanation
일곱 항목은 ①원파일·입력 해시 ②원행 키와 관측 단위 ③원문→수치 변환 ④가용·미관측 분모 ⑤함수의 인자·반환 ⑥실제 출력과 단위 ⑦실행 버전·코드 해시입니다. 예를 들어 점포 완전짝 384개의 FTE 평균 변화는 코드로 재현해도 정책의 인과효과로 인증되지 않습니다. 다른 동료가 같은 파일을 처음부터 실행해 분모와 결과를 확인하도록 합니다.
Explain (1) source file/input hash, (2) source keys and unit of observation, (3) text-to-number conversion, (4) available/unavailable denominators, (5) arguments and returns, (6) actual output and units, and (7) runtime version/code hash. Reproducing the 384-store-pair mean FTE change does not certify a causal policy effect. Have a colleague rerun the retained files from the beginning.
자료별 확보일·원행 식별·단위·이용 조건은 출처 기록을 확인하세요. 학습 사본은 제공처의 현재 최신 자료와 다를 수 있습니다.Consult each source record for retrieval dates, row identifiers, units and terms. Teaching copies can differ from current provider releases.