问题
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