Reading CSV & Working with Dataframes in R — Comprehensive Notes
1. Reading CSV Data into R You can read CSV files using [Link](). The file is stored as a dataframe.
getwd() hdi <- [Link]("[Link]") head(hdi) head(hdi, 10) tail(hdi) str(hdi) summary(hdi)
2. Understanding Dataframes A dataframe is a table-like R object containing rows and columns. Each
column can be numeric, character, factor etc.
Column Names colnames(hdi) hdi_col <- colnames(hdi)
Rename Columns Method 1: colnames(hdi)[1] <- "HDI Rank"
Method 2 (using tidyverse/dplyr): hdi <- rename(hdi, countrycode = countryshort)
3. Subsetting Dataframes Use [row, column] to extract parts of a dataframe. hdi[4, ] # 4th row hdi[ ,4] #
4th column hdi[1:3, 4:6] # rows 1–3, columns 4–6 hdi$hdilevel # single column as vector
Conditional Subsetting hdi_more <- hdi[hdi$hdi >= 0.5, ] nrow(hdi_more)
4. Working with Categorical Variables Convert character variables to factors (useful for modeling &
grouping): hdi <- mutate(hdi, hdilevel = factor(hdilevel)) hdi <- mutate(hdi, continentregion =
factor(continentregion), region = factor(region)) fct_count(hdi$hdilevel)
5. Summary Statistics var(hdi$lifeexp) cov(hdi$lifeexp, hdi$gnipc) cor(hdi$hdi, hdi$meanschool)
6. Skewness library(moments) skewness(hdi$hdi)
7. Basic Plots hist(hdi$hdi, col="yellow") plot(hdi$gnipc, hdi$lifeexp)
8. The Pipe Operator (%>%) The pipe passes the dataframe into functions to avoid repeatedly typing
the dataframe name. hdi_new <- hdi %>% filter(hdi >= 0.5)
9. Summaries by Category hdi %>% group_by(hdilevel) %>% summarise(mean_pci = mean(gnipc)) hdi
%>% group_by(hdilevel) %>% summarise(mean_pci = mean(gnipc), mean_hdi = mean(hdi))
10. Saving Summaries hdi_income <- hdi %>% group_by(hdilevel) %>% summarise(mean_pci =
mean(gnipc), mean_hdi = mean(hdi))