Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr Update a cell in a data.frame

Tags:

r

dplyr

df <-data.frame(x=c(1:5),y=c(letters[1:5]))

Let's say I want to modify the last row,

update.row<-filter(df,x==5) %>% mutate(y="R")

How do I update this row into the data.frame ? The only way, I found albeit a strange way is to do an anti-join and append the results.

df <-anti_join(df,update.row,by="x") %>%
     bind_rows(update.row)

However, it seems like a very inelegant way to achieve a simple task. Any ideas are much appreciated...

like image 962
prog_guy Avatar asked Jan 21 '16 02:01

prog_guy


People also ask

Does dplyr work with data frame?

All of the dplyr functions take a data frame (or tibble) as the first argument. Rather than forcing the user to either save intermediate objects or nest functions, dplyr provides the %>% operator from magrittr.

What does mutate () do in R?

In R programming, the mutate function is used to create a new variable from a data set. In order to use the function, we need to install the dplyr package, which is an add-on to R that includes a host of cool functions for selecting, filtering, grouping, and arranging data.

What is transmute R?

Source: R/mutate.R. mutate.Rd. mutate() adds new variables and preserves existing ones; transmute() adds new variables and drops existing ones. New variables overwrite existing variables of the same name. Variables can be removed by setting their value to NULL .


2 Answers

With data.table, we can assign (:=) the value to the rows where i is TRUE. It is very efficient as the assignment is done in place.

library(data.table)
setDT(df)[x==5, y:="R"]
df
#   x y
#1: 1 a
#2: 2 b
#3: 3 c
#4: 4 d
#5: 5 R

As the OP mentioned about the last row, a more general way is

setDT(df)[.N, y:= "R"]

Or as @thelatemail mentioned, if we want to replace any row just mention the row index in i i.e. in this case 5.

setDT(df)[5, y:="R"]
like image 193
akrun Avatar answered Nov 04 '22 04:11

akrun


If you are insistant on dplyr, perhaps

df <-data.frame(x=c(1:5),y=c(letters[1:5]))

library(dplyr)
df %>%
    mutate(y = as.character(y)) %>%
    mutate(y = ifelse(row_number()==n(), "R", y))

#  x y
#1 1 a
#2 2 b
#3 3 c
#4 4 d
#5 5 R
like image 40
tospig Avatar answered Nov 04 '22 02:11

tospig