0
0
R Programmingprogramming~20 mins

Adding and removing columns in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Column Mastery in R
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of adding a new column with cbind
What is the output of this R code after adding a new column using cbind?
R Programming
df <- data.frame(a = 1:3, b = 4:6)
df <- cbind(df, c = c(7, 8, 9))
print(df)
AError in cbind(df, c = c(7, 8, 9)) : object 'c' not found
B
  a b
1 1 4
2 2 5
3 3 6
c 7 8 9
C
  a b c
1 1 4 7
2 2 5 8
3 3 6 9
D
  a b c
1 7 8 9
2 1 4 7
3 2 5 8
Attempts:
2 left
💡 Hint
Remember that cbind adds columns side by side and keeps row order.
Predict Output
intermediate
2:00remaining
Result of removing a column using NULL assignment
What will be the result of this R code after removing column 'b' by assigning NULL?
R Programming
df <- data.frame(a = 1:3, b = 4:6, c = 7:9)
df$b <- NULL
print(df)
A
  a b
1 1 4
2 2 5
3 3 6
B
  a b c
1 1 4 7
2 2 5 8
3 3 6 9
CError: object 'b' not found
D
  a c
1 1 7
2 2 8
3 3 9
Attempts:
2 left
💡 Hint
Assigning NULL to a column removes it from the data frame.
🔧 Debug
advanced
2:00remaining
Why does this code fail to add a column?
This code tries to add a new column 'd' to the data frame but fails. What is the error?
R Programming
df <- data.frame(a = 1:3, b = 4:6)
df$d <- c(7, 8)
print(df)
ANo error, column 'd' added with NA for missing values
BError: replacement has 2 rows, data has 3
CError: object 'd' not found
DColumn 'd' added with recycled values
Attempts:
2 left
💡 Hint
Check if the length of the new column matches the number of rows.
Predict Output
advanced
2:00remaining
Output after removing multiple columns with subset
What is the output of this R code after removing columns 'b' and 'c' using subset?
R Programming
df <- data.frame(a = 1:3, b = 4:6, c = 7:9)
df2 <- subset(df, select = -c(b, c))
print(df2)
A
  a
1 1
2 2
3 3
B
  a b c
1 1 4 7
2 2 5 8
3 3 6 9
CError in subset(df, select = -c(b, c)) : invalid subscript type
D
  b c
1 4 7
2 5 8
3 6 9
Attempts:
2 left
💡 Hint
The select = -c(...) syntax removes specified columns.
🧠 Conceptual
expert
2:00remaining
Why is using transform() safer than direct assignment for adding columns?
Which reason best explains why transform() is often preferred over direct assignment (e.g., df$newcol <- ...) when adding columns to a data frame?
ABecause <code>transform()</code> returns a new data frame and avoids modifying the original by reference
BBecause direct assignment always causes errors if the new column length differs
CBecause <code>transform()</code> automatically removes NA values from the new column
DBecause direct assignment cannot add columns with names longer than 5 characters
Attempts:
2 left
💡 Hint
Think about how data frames are copied or modified in R.