0
0
R Programmingprogramming~20 mins

Accessing columns ($, []) in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Column Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of accessing columns with $ vs []
What is the output of the following R code?
R Programming
df <- data.frame(a = 1:3, b = 4:6)
print(df$a)
print(df["a"])
print(class(df$a))
print(class(df["a"]))
A
[1] 1 2 3
[1] 1 2 3
[1] "integer"
[1] "integer"
B
[1] 1 2 3
  a
1 1
2 2
3 3
[1] "data.frame"
[1] "integer"
C
[1] 1 2 3
  a
1 1
2 2
3 3
[1] "integer"
[1] "data.frame"
DError in print(df$a) : object 'a' not found
Attempts:
2 left
💡 Hint
Remember that $ returns a vector, while [] returns a data frame.
Predict Output
intermediate
2:00remaining
Accessing multiple columns with []
What is the output of this R code snippet?
R Programming
df <- data.frame(x = 10:12, y = 20:22, z = 30:32)
print(df[c("x", "z")])
A
   x  y  z
1 10 20 30
2 11 21 31
3 12 22 32
B[1] 10 11 12 30 31 32
CError in df[c("x", "z")] : invalid subscript type 'character'
D
   x  z
1 10 30
2 11 31
3 12 32
Attempts:
2 left
💡 Hint
Using [] with a vector of column names returns those columns as a data frame.
Predict Output
advanced
2:00remaining
Difference between df$col and df[, "col"]
What is the output of this R code?
R Programming
df <- data.frame(a = 1:2, b = c("x", "y"))
print(class(df$a))
print(class(df[, "a"]))
print(class(df[, "a", drop = FALSE]))
A
[1] "integer"
[1] "integer"
[1] "data.frame"
B
[1] "integer"
[1] "integer"
[1] "integer"
C
[1] "integer"
[1] "data.frame"
[1] "data.frame"
D
[1] "data.frame"
[1] "integer"
[1] "data.frame"
Attempts:
2 left
💡 Hint
The drop argument controls whether the result is simplified to a vector.
Predict Output
advanced
2:00remaining
Accessing columns with numeric indices
What is the output of this R code?
R Programming
df <- data.frame(m = 5:7, n = 8:10)
print(df$`1`)
print(df[1])
print(df[[1]])
A
NULL
  m
1 5
2 6
3 7
[1] 5 6 7
B
Error: unexpected numeric constant
  m
1 5
2 6
3 7
[1] 5 6 7
C
Error: object '1' not found
  m
1 5
2 6
3 7
[1] 5 6 7
D
NULL
Error in df[1] : subscript out of bounds
[1] 5 6 7
Attempts:
2 left
💡 Hint
The $ operator expects a name, not a number.
🧠 Conceptual
expert
3:00remaining
Why does df$col fail but df[["col"]] works?
Given a data frame df with a column named "123", which of the following statements is true?
ABoth df$123 and df[["123"]] fail because column names cannot start with numbers.
Bdf$123 fails because $ expects a valid variable name, but df[["123"]] works because it accepts any string as column name.
Cdf$123 works because $ accepts numeric column names.
Ddf$123 works only if the column is numeric, df[["123"]] works for any type.
Attempts:
2 left
💡 Hint
Think about how $ operator interprets names versus [[ operator.