dplyr Update a cell in a data.frame

我怕爱的太早我们不能终老 提交于 2021-02-20 18:52:44

问题


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...


回答1:


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



回答2:


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"]


来源:https://stackoverflow.com/questions/34914536/dplyr-update-a-cell-in-a-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!