Forge
Forge

Reputation: 1687

change value from last column last row in R dataframe using dplyr

I want to change the last column last value from R dataframe.

I know I can use base R this way:

df[nrow(), ncol()] <- "my value"

But I would like to use tidy approach

What i tried so far:

# the last row and column to mutate by name

df %>% slice(1) %>% mutate(my_last_column="my value") 

But I really would like to do it without knowing the column name.

Upvotes: 2

Views: 2187

Answers (1)

Ben
Ben

Reputation: 30549

Here are a few options using dplyr and example mtcars data.frame:

To get the last row, try:

library(dplyr)

mtcars %>%
  filter(row_number() == n())

or

mtcars %>%
  slice_tail(n = 1)

To get the last column, try:

mtcars %>%
  select_at(ncol(.))

or

mtcars %>%
  select(tail(names(.), 1))

If you want to mutate the last row and last column, you could try this.

mtcars %>%
  mutate_at(ncol(.), funs(ifelse(row_number() == n(), -1, .)))

This would change the value in the last row and column to -1.

Upvotes: 4

Related Questions