从数据帧过滤获得的子集中批量更新 [英] Bulk update in subset obtained from dataframe filtering

查看:23
本文介绍了从数据帧过滤获得的子集中批量更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我根据以下 2 个条件对其进行过滤:

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

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

我想批量更新上述子集的特定列的值(比方说status)类似的东西

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.

推荐答案

You can do

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

使用replace

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

<小时>

我们也可以将其集成到 dplyr 链中.

library(dplyr)

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

或使用 case_when

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

subset 根据提供的条件过滤数据框并且不更新它们.

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

这篇关于从数据帧过滤获得的子集中批量更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆