0
0
R Programmingprogramming~5 mins

Modifying and adding elements in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
How do you change the value of an element in a vector in R?
You assign a new value to the element using its index. For example, vec[2] <- 10 changes the second element to 10.
Click to reveal answer
beginner
What function can you use to add elements to the end of a vector?
You can use the c() function to combine vectors or add elements. For example, vec <- c(vec, 5) adds 5 to the end.
Click to reveal answer
beginner
How do you add a new column to a data frame in R?
Assign a vector to a new column name. For example, df$new_col <- c(1,2,3) adds a column named 'new_col'.
Click to reveal answer
intermediate
How can you modify an element inside a list in R?
Use double brackets with the element name or index. For example, mylist[["item"]] <- 42 changes the 'item' element.
Click to reveal answer
intermediate
What happens if you assign a value to an index outside the current length of a vector?
R extends the vector and fills missing elements with NA. For example, vec[5] <- 10 makes elements 3 and 4 NA if they didn't exist.
Click to reveal answer
Which syntax correctly adds a new element 7 to the end of vector v?
Av <- c(v, 7)
Bv[7] <- v
Cv + 7
Dappend(v, 7)
How do you change the third element of vector x to 100?
Ax(3) = 100
Bx[3] <- 100
Cx <- 100[3]
Dx[[3]] <- 100
Which is the correct way to add a new column named 'age' to data frame df?
Adf <- c(df, age)
Bdf[age] <- c(25, 30, 35)
Cdf(age) <- c(25, 30, 35)
Ddf$age <- c(25, 30, 35)
What happens if you assign a value to vec[10] when vec has length 5?
AVector extends; elements 6 to 9 become NA
BError: index out of bounds
CNothing changes
DVector shrinks to length 10
How do you modify the element named 'score' in a list lst?
Alst[score] <- new_value
Blst.score <- new_value
Clst[['score']] <- new_value
Dlst(score) <- new_value
Explain how to modify an element in a vector and add a new element at the end in R.
Think about using brackets for modification and c() for adding.
You got /3 concepts.
    Describe how to add a new column to a data frame and how to modify an element inside a list.
    Remember data frames and lists have different ways to access elements.
    You got /3 concepts.