0
0
R Programmingprogramming~5 mins

Adding and removing columns in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
How do you add a new column to a data frame in R?
You can add a new column by assigning a vector to a new column name using the $ operator or bracket notation. For example, df$new_column <- c(1, 2, 3) adds a column named new_column.
Click to reveal answer
beginner
What is the syntax to remove a column from a data frame in R?
You can remove a column by setting it to NULL: df$column_to_remove <- NULL. This deletes the column from the data frame.
Click to reveal answer
intermediate
What happens if you assign a vector of different length than the number of rows when adding a column?
R will recycle the vector to match the number of rows, repeating the values to fill the column. A warning is given if its length does not divide evenly into the number of rows.
Click to reveal answer
intermediate
How can you add multiple columns at once to a data frame?
You can add multiple columns by assigning a data frame or list to new columns. For example, df[c('col1', 'col2')] <- list(c(1,2), c(3,4)) adds two columns.
Click to reveal answer
intermediate
Can you remove multiple columns at once? How?
Yes, by setting multiple columns to NULL using their names in brackets: df[c('col1', 'col2')] <- NULL removes both columns.
Click to reveal answer
Which of the following adds a new column named 'age' with values 25, 30, 35 to data frame df?
Adf$age = 25
Bdf['age'] = 25:35
Cdf$age <- c('25', '30', '35')
Ddf$age <- c(25, 30, 35)
How do you remove the column 'salary' from data frame df?
Adf$salary <- NULL
Bdf$salary <- NA
Cdf <- df[-salary]
Dremove(df$salary)
What happens if you add a column with a vector shorter than the number of rows?
AThe column is filled with NA
BR throws an error always
CR recycles the vector values to fill the column
DThe data frame shrinks to match vector length
Which syntax adds two columns 'x' and 'y' at once to df?
Adf[c('x', 'y')] <- list(c(1,2), c(3,4))
Bdf$x, df$y <- c(1,2), c(3,4)
Cdf[c('x', 'y')] <- c(1,2,3,4)
Ddf$xy <- c(1,2,3,4)
How to remove columns 'a' and 'b' from df in one step?
Adf$a <- NULL; df$b <- NULL
Bdf[c('a', 'b')] <- NULL
Cdf <- df[-c('a', 'b')]
Dremove(df$a, df$b)
Explain how to add a new column to a data frame in R and what happens if the vector length differs from the number of rows.
Think about how R handles vectors when adding columns.
You got /3 concepts.
    Describe the methods to remove one or multiple columns from a data frame in R.
    Consider how NULL affects data frame columns.
    You got /3 concepts.