11

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?

2
  • 1
    if you have to use dplyr I think the only method is using a combination of mutate and if_else to specify the row/col to modify. see this
    – EJJ
    May 15, 2020 at 14:41
  • 2
    @EJJ, unfortunately that seems to be the only solution. I was really hoping dplyr had generated a new way of solving this problem since 2016 May 15, 2020 at 14:43

2 Answers 2

18

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))
4

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.