简体   繁体   中英

R rolling function based upon columns

In R , I am attempting to create a column of a local min/max, based on 2 other columns.

In particular, I want the 3rd column to be a "current" column, and when x1 > current or x2 < current I want to update currentValue. Otherwise, it should be the previous currentValue

Initially, I set the entire y1 column to my starting value. As can be seen, Row 5 should be using the currentValue of 5, and no change should be made. However, the comparison is being made to the value of 2 instead.

Any help would be greatly appreciated as I am unfamiliar with applying custom rolling functions in R . It seems like there should be an elegant solution for this, but a few other similar posts require a lot of code to accomplish this.

> c1 <- c(1,1,2,5,4,3,2,1)
> c2 <- c(2,3,3,6,6,4,4,2)
> c3 <- 2
> tempData <- data.frame(c1,c2,c3)
> names(tempData) <- c("x1", "x2", "currentValue")
> tempData
  x1 x2 currentValue
1  1  2            2
2  1  3            2
3  2  3            2
4  5  6            2
5  4  6            2
6  3  4            2
7  2  4            2
8  1  2            2
> 
> tempData$currentValue <- ifelse (tempData$x1 > lag(tempData$currentValue), tempData$x1, ifelse(tempData$x2 < lag(tempData$currentValue), tempData$x2, lag(tempData$currentValue)))
> tempData
  x1 x2 currentValue
1  1  2           NA
2  1  3            2
3  2  3            2
4  5  6            5
5  4  6            4
6  3  4            3
7  2  4            2
8  1  2            2

I think this code could help you. It is problematic to apply that lag function in the ifelse statement, in you code is not shifting the values of the column I guess, anyway, check this following code.

    c1 <- c(1,1,2,5,4,3,2,1)
c2 <- c(2,3,3,6,6,4,4,2)
c3 <- 2
tempData <- data.frame(c1,c2,c3)
names(tempData) <- c("x1", "x2", "currentValue")
tempData
tempData$x1.lag <- c(NA, tempData$x1[1:7] )
tempData$x2.lag <- c(NA, tempData$x2[1:7] )
tempData
tempData$currentValue <- ifelse (tempData$x1 > tempData$x1.lag , tempData$x1,
                                 ifelse( tempData$x2 < tempData$x2.lag, tempData$x2, tempData$currentValue))
tempData$x1.lag <- NULL
tempData$x2.lag <- NULL
tempData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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