'Modify a single cell value in dplyr

Let's say I have the following dataset:

dat <- read.table(text="id_1 id_2 
                  123 NA
                  456 NA
                  NA 3
                  NA 1
                  NA 1", header=T)

I'd like to change the id_1 value for the first row. I'd like to do something like this:

dat %>% slice(1) %>% mutate(id_1 == "new_id") %>% unslice()

However there doesn't appear to be an unslice command, so I'm left with a dataframe that has a single row (the modified). Is there a clean way do get back the original dataset after modification in-place?



Solution 1:[1]

If I understand your question correctly and you just want to change the value in the column id_1 (rather than changing the column name), you can access the row with the row_number command.

dat %>% 
    mutate(id_1 = ifelse(row_number() == 1, "new_id",id_1))

If you want to do this with further rows as well, consider:

dat %>% 
    mutate(id_1 = case_when(row_number() == 1 ~"new_id1", 
                            row_number() == 2 ~"new_id2",
                            TRUE ~ id_1))

etc.

Note that this will of course change the column type to a character type. If you don't want to access the row by it's number, you can also do this via the exact value that you want to change.

dat %>% 
      mutate(id_1 = ifelse(id_1 == 456, "new_id",id_1))

Solution 2:[2]

You could use mutate_at with replace to do that.

library(dplyr)
dat %>%
  mutate_at(vars(id_1), function(x) replace(x, 
                      row_number(x) == 1, 
                      "new_id"))

# id_1 id_2
# 1 new_id   NA
# 2    456   NA
# 3   <NA>    3
# 4   <NA>    1
# 5   <NA>    1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jonathan V. Solórzano