remove an element from the end of an array in r

To remove an element from the end of an array in R, you can use the following code:

main.r
myArray <- myArray[-length(myArray)]
37 chars
2 lines

Here, myArray is the name of the array you want to modify. The length function gives the length of the array, and [-length(myArray)] selects all but the last element of the array. The result is that the last element is "popped" off the end of the array.

Alternatively, if you want to permanently remove the last element from the array, you can use the mutate function from the dplyr package as follows:

main.r
library(dplyr)
myArray <- myArray %>% slice(-n())
50 chars
3 lines

Here, slice(-n()) means to remove the last row of the data frame. Since arrays are stored as data frames in R, this method can also be used to remove the last element from an array.

related categories

gistlibby LogSnag