gpt4 book ai didi

r - 数据框 - 在 R 中添加具有条件的出现次数

转载 作者:行者123 更新时间:2023-12-05 05:42:03 25 4
gpt4 key购买 nike

我在尝试弄清楚如何执行以下操作时遇到了一些困难。我想映射我之前有多少天的高销售价格变化。例如,我在第 10 天有一个价格变化,高销售指标会告诉我任何大于或等于 10 的销售。需要我的算法来计算连续高销售的数量。

在这种情况下,它应该返回 5(第 5 天到第 9 天)

出于示例目的,数据框称为 df .代码:

#trying to create a while loop that will check if lag(high_sales) is 1, if yes it will count until
#there's a lag(high_sales) ==0

#loop is just my dummy variable that will take me out of the while loop
count_sales<-0
loop<-0
df<- df %>% mutate(consec_high_days= ifelse(price_change > 0, while(loop==0){
if(lag(High_sales_ind)==1){
count_sales<-count_sales +1}
else{loop<-0}
count_sales},0))


<表类="s-表"><头><日>日 价格price_change销售额High_sales_ind<正文>150121250603505045040550101650101750101850121950141107230117020

这是我的错误信息:

Warning: Problem with mutate() column consec_high_days.i consec_high_days = ifelse(...).i the condition has length > 1 and only the first element will be used

Warning: Problem with mutate() column consec_high_days.i consec_high_days = ifelse(...).i 'x' is NULL so the result will be NULL

Error: Problem with mutate() column consec_high_days.i consec_high_days = ifelse(...).x replacement has length zero

如有任何帮助,我们将不胜感激。

最佳答案

这是一个非常不优雅的蛮力答案,虽然希望比我更好的人可以提供更优雅的答案 - 但要获得所需的数据集,您可以尝试:

df <- read.table(text = "day    price   price_change    sales   High_sales_ind
1 5 0 12 1
2 5 0 6 0
3 5 0 5 0
4 5 0 4 0
5 5 0 10 1
6 5 0 10 1
7 5 0 10 1
8 5 0 12 1
9 5 0 14 1
10 7 2 3 0
11 7 0 2 0", header = TRUE)

# assign consecutive instances of value
df$seq <- sequence(rle(as.character(df$sales >= 10))$lengths)

# Find how many instance of consecutive days occurred before price change
df <- df %>% mutate(lseq = lag(seq))

# define rows you want to keep and when to end
keepz <- df[df$price_change != 0, "lseq"]
end <- as.numeric(rownames(df[df$price_change != 0,]))-1

df_want <- df[keepz:end,-c(6:7)]

输出:

#     day price price_change sales High_sales_ind
# 5 5 5 0 10 1
# 6 6 5 0 10 1
# 7 7 5 0 10 1
# 8 8 5 0 12 1
# 9 9 5 0 14 1

关于r - 数据框 - 在 R 中添加具有条件的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72134909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com