R Data Frames

Working with data frames in R

Creating Data Frames

df <- data.frame( # create data frame
    name = c("Alice", "Bob", "Charlie"),
    age = c(25, 30, 35),
    score = c(85, 90, 95)
)

Accessing Data

df$name # access column by name
df[1, ] # first row
df[, 1] # first column
df[1, 2] # element at row 1, col 2
df[1:2, ] # first two rows

Data Frame Info

nrow(df) # number of rows
ncol(df) # number of columns
dim(df) # dimensions (rows, cols)
names(df) # column names
str(df) # structure of data frame
summary(df) # statistical summary

View Data

head(df) # first 6 rows
tail(df) # last 6 rows
head(df, 10) # first 10 rows
View(df) # open viewer

Filtering Data

df[df$age > 25, ] # filter rows where age > 25
subset(df, age > 25) # subset function
df[df$name == "Alice", ] # filter by name

Adding Data

df$city <- c("NYC", "LA", "SF") # add new column
df <- rbind(df, new_row) # add row
df <- cbind(df, new_col) # add column