简体   繁体   English

如何为特定条件替换列中的值?

[英]How to replace values in a column for a specific condition?

I want to change the orders to 100 if my revenues > 1900 and the day is not "sun" Can someone please help.如果我的收入 > 1900 并且当天不是“太阳”,我想将订单更改为 100 有人可以帮忙吗? Any help will be appreciated.任何帮助将不胜感激。

my data:我的数据:

df1 <- structure(list(day = c("mon", "tue", "wed", "thu", "fri", "sat", 
"sun"), orders = c(90L, 80L, 50L, 20L, 5L, 20L, 95L), revenues = c(1800L, 
2000L, 1000L, 2000L, 100L, 400L, 1900L)), class = "data.frame", row.names = c("Day1", 
"Day2", "Day3", "Day4", "Day5", "Day6", "Day7"))

Create a logical vector and use that index to do the assignment创建一个逻辑向量并使用该索引进行分配

i1 <- with(df1, day != 'sun' & revenues > 1900)
df1$orders[i1] <- 100

-output -输出

> df1
     day orders revenues
Day1 mon     90     1800
Day2 tue    100     2000
Day3 wed     50     1000
Day4 thu    100     2000
Day5 fri      5      100
Day6 sat     20      400
Day7 sun     95     1900
library(dplyr)

df %>% 
  mutate(orders = ifelse(revenues > 1900 & day != "sun", 100, orders))

     day orders revenues
Day1 mon     90     1800
Day2 tue    100     2000
Day3 wed     50     1000
Day4 thu    100     2000
Day5 fri      5      100
Day6 sat     20      400
Day7 sun     95     1900

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM