# Base-R reproduction of the public-data algebra/unit chapter.
# Run from this folder: Rscript --vanilla chapter01.R
# CSV blanks stay NA; no package installation is required.
source_file <- if (file.exists("penguins.csv")) "penguins.csv" else "실제데이터/penguins.csv"
penguins <- read.csv(source_file, na.strings=c("", "NA"), fileEncoding="UTF-8-BOM")
observed <- !is.na(penguins$body_mass_g)
complete <- complete.cases(penguins[,c("body_mass_g","flipper_length_mm")])
penguins$body_mass_kg <- penguins$body_mass_g/1000
first_five <- penguins$body_mass_g[1:5]
mean_observed <- mean(first_five,na.rm=TRUE)
zero_filled <- first_five; zero_filled[is.na(zero_filled)] <- 0
mean_zero <- mean(zero_filled)
stopifnot(nrow(penguins)==344L,sum(observed)==342L,sum(complete)==342L,
          is.na(penguins$body_mass_g[4]),mean_observed==3562.5,mean_zero==2850,
          max(abs(penguins$body_mass_kg[observed]*1000-penguins$body_mass_g[observed]))<1e-8)
write.csv(penguins[,c("row_id","species","body_mass_g","body_mass_kg")],"chapter01-results-R.csv",row.names=FALSE,na="",fileEncoding="UTF-8")
cat("rows",nrow(penguins),"observed mass",sum(observed),"mass/flipper pairs",sum(complete),"\n")
cat("observed mean (first five)",mean_observed,"zero-filled mean",mean_zero,"\n")
