Expanding a Data Frame in R – Adding Columns and Rows
In R, data frames are flexible structures that can be expanded dynamically by adding new columns (variables) or rows (observations).
Adding a Column to a Data Frame
You can add a new column simply by assigning values using the $ operator or bracket notation:
📌 Using $:
r
Copy code
df$new_column <- c(10, 20, 30)
📌 Using [ , ] notation:
r
Copy code
df[ , "new_column"] <- c(10, 20, 30)
➡️ The length of the new column vector must match the number of rows in the data frame.
✅ 2. Adding a Row to a Data Frame
Use rbind() to bind a new row (as a list or another data frame) to the existing one.
📌 Example:
r
Copy code
new_row <- data.frame(name = "Alex", age = 25)
df <- rbind(df, new_row)
➡️ Column names and data types must match the existing data frame.