Bulk update in subset obtained from dataframe filtering [duplicate]

我是研究僧i 提交于 2019-12-02 21:57:45

问题


I have a dataframe, which I filter based on 2 condition as follow:

subset(sales_data, month == 'Jan' & dept_name == 'Production')`

I want to bulk update the value of a particular column(let's say status) of above subset Something like

subset(sales_data, month == 'Jan' & dept_name == 'Production')["status"] <- "Good result"`

I am not sure, how I can do this.


回答1:


You could do

sales_data$status[
 sales_data$month == 'Jan' & sales_data$dept_name == 'Production'] <- "Good result"

Using replace

sales_data$status <- with(sales_data, 
     replace(status, month == 'Jan' & dept_name == 'Production', "Good result"))

We can also integrate this in dplyr chain.

library(dplyr)

sales_data %>%
   mutate(status = replace(status, month == 'Jan' & dept_name == 'Production', 
                   "Good result"))

or with case_when

sales_data %>%
 mutate(status = case_when(month == 'Jan' & dept_name =='Production'~"Good result",
                           TRUE ~ status))

subset filter the dataframe based on conditions provided and does not update them.



来源:https://stackoverflow.com/questions/55507593/bulk-update-in-subset-obtained-from-dataframe-filtering

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