3

我一直在尝试计算具有条件的变量的最小值。我有以下数据:

Data
Date       Net Price 
2013-12-01  A   39  
2013-12-01  B   23  
2013-12-01  C   25  
2013-12-08  A   52  
2013-12-08  B   12  
2013-12-08  C   19  
2013-12-15  A   32  
2013-12-15  B   36  
2013-12-15  C   40  

我想在 A 中添加一列最低价格,即 Min(B,C) 和 B,即 Min(A,B),依此类推。

Date       Net Price Min 
2013-12-01  A   39  23
2013-12-01  B   23  25
2013-12-01  C   25  23
2013-12-08  A   52  12
2013-12-08  B   12  19
2013-12-08  C   19  12
2013-12-15  A   32  36
2013-12-15  B   36  32
2013-12-15  C   40  32

有人可以帮我在网络不等于拥有的日期之前找到最小值。

谢谢

4

2 回答 2

2

你也可以使用这个:

f <- function(x){m <- min(x); ifelse(x==m, min(x[x>m]), m)}
within(Data, Min <- ave(Price, Date, FUN=f))

结果:

        Date Net Price Min
1 2013-12-01   A    39  23
2 2013-12-01   B    23  25
3 2013-12-01   C    25  23
4 2013-12-08   A    52  12
5 2013-12-08   B    12  19
6 2013-12-08   C    19  12
7 2013-12-15   A    32  36
8 2013-12-15   B    36  32
9 2013-12-15   C    40  32
于 2013-09-25T18:46:56.667 回答
1

I wouldn't say this is the most elegant solution, but it works.

data <- read.table(text='Date       Net Price 
2013-12-01  A   39  
2013-12-01  B   23  
2013-12-01  C   25  
2013-12-08  A   52  
2013-12-08  B   12  
2013-12-08  C   19  
2013-12-15  A   32  
2013-12-15  B   36  
2013-12-15  C   40  ',header=TRUE)

sp <- split(data,data$Date)
mindrop1 <- function(j) sapply(1:nrow(j),function(i) min(j$Price[-i]))
data$Min <- unlist(lapply(sp, mindrop1))

> data
        Date Net Price Min
1 2013-12-01   A    39  23
2 2013-12-01   B    23  25
3 2013-12-01   C    25  23
4 2013-12-08   A    52  12
5 2013-12-08   B    12  19
6 2013-12-08   C    19  12
7 2013-12-15   A    32  36
8 2013-12-15   B    36  32
9 2013-12-15   C    40  32
于 2013-09-25T18:41:13.997 回答