r - dplyr Update a cell in a data.frame -
df <-data.frame(x=c(1:5),y=c(letters[1:5])) let's want modify last row,
update.row<-filter(df,x==5) %>% mutate(y="r") how update row data.frame ? way, found albeit strange way anti-join , append results.
df <-anti_join(df,update.row,by="x") %>% bind_rows(update.row) however, seems inelegant way achieve simple task. ideas appreciated...
with data.table, can assign (:=) value rows i true. efficient assignment done in place.
library(data.table) setdt(df)[x==5, y:="r"] df # x y #1: 1 #2: 2 b #3: 3 c #4: 4 d #5: 5 r as op mentioned last row, more general way is
setdt(df)[.n, y:= "r"] or @thelatemail mentioned, if want replace row mention row index in i i.e. in case 5.
setdt(df)[5, y:="r"]
Comments
Post a Comment