0
0
R Programmingprogramming~20 mins

Modifying and adding elements in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
R Vector and List Modifier
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this R code modifying a vector element?
Consider the following R code that modifies an element in a vector. What will be printed?
R Programming
vec <- c(10, 20, 30, 40)
vec[2] <- 25
print(vec)
A[1] 10 20 30 40
B[1] 10 25 30 40
C[1] 25 20 30 40
D[1] 10 25 25 40
Attempts:
2 left
💡 Hint
Remember that indexing in R starts at 1 and you can assign a new value to a specific position.
Predict Output
intermediate
2:00remaining
What happens when adding a new element to a list in R?
What will be the output of this R code that adds a new element to a list?
R Programming
my_list <- list(a=1, b=2)
my_list$c <- 3
print(my_list)
AError in my_list$c <- 3 : object is not a list
B[1] 1 2 3
C
$a
[1] 1

$b
[1] 2

$c
[1] 3
Dlist(a=1, b=2, c=3)
Attempts:
2 left
💡 Hint
In R, you can add named elements to a list using the $ operator.
🔧 Debug
advanced
2:00remaining
Why does this R code produce an error when modifying a vector element?
Identify the error in this R code and explain why it happens.
R Programming
vec <- c(1, 2, 3)
vec[4] <- 5
print(vec)
ANo error; output is [1] 1 2 3 5
BWarning: NAs introduced by coercion
CError: subscript out of bounds
DError: object 'vec' not found
Attempts:
2 left
💡 Hint
In R, vectors can be extended by assigning to an index beyond their current length.
Predict Output
advanced
2:00remaining
What is the output after modifying a data frame column in R?
Given this R code that modifies a data frame column, what will be printed?
R Programming
df <- data.frame(x = 1:3, y = c('a', 'b', 'c'))
df$x[2] <- 10
print(df)
A
  x y
1  1 a
2 10 b
3  3 c
B
  x y
1  1 a
2  2 b
3  3 c
CError: replacement has length zero
D
  x y
1 10 a
2 10 b
3 10 c
Attempts:
2 left
💡 Hint
You can modify specific elements of a data frame column by indexing.
🧠 Conceptual
expert
2:00remaining
How does R handle adding elements beyond current vector length?
In R, what happens when you assign a value to an index beyond the current length of a vector?
AR truncates the vector to the assigned index and assigns the value
BR throws an error: subscript out of bounds
CR ignores the assignment silently without changing the vector
DR extends the vector, filling intermediate positions with NA, then assigns the value
Attempts:
2 left
💡 Hint
Think about what happens if you assign to an index that does not yet exist in the vector.