1

我之前问过一个关于这个的问题,这个问题被迁移到了 stats.stackexchange

从那里得到答案后,我对 R 中的实现有一些问题来解决这个问题,并认为我应该在这里问他们。

这就是我想要制作的:

对于每个权益,我有两个单独的列,价格和时间。如果股权 X 存在时间但股权 Y 不存在,则应将先前的价格放入向量中,反之亦然。

if循环是这里的解决方案吗?谢谢你的帮助。

如下例:

X           Y   
price   time   price   time
10     540     20  540
11     541     21  541
12     542     22  543
13     544     23  544
14     545     24  545

price   time   price   time
10     540     20  540
11     541     21  541
12     542     21  542
12     543     22  543
13     544     23  544
14     545     24  545
4

1 回答 1

5
x <- read.table(text = "price   time
 10     540
 11     541
 12     542
 13     544
 14     545", header = TRUE);

 y <- read.table(text = "price   time
  20  540
  21  541
  22  543
  23  544
  24  545", header = TRUE)

 big <- merge(x, y, all = TRUE, by = "time")
 big
 #   time price.x price.y
 # 1  540      10      20
 # 2  541      11      21
 # 3  542      12      NA
 # 4  543      NA      22
 # 5  544      13      23
 # 6  545      14      24

library(zoo)
big$price.x <- na.locf(big$price.x)
big$price.y <- na.locf(big$price.y)

如果第一个值是一个NA或什至是第二个值等等,NA我认为你想为所有先前的条目使用第一个非 NA 值?

例如

NA,1,2,3,NA
# changed to
1,1,2,3,3

如果是这样,这将起作用:

replaceKEEPFIRST <- function(x) {
x2    <- na.locf(x)
diffx <- length(x) - length(x2)
val   <- c(rep(x2[1],diffx),x2)
return(val)
}

myx <- c(NA,1,2,3,NA)
myy <- c(1,2,3,NA)
replaceKEEPFIRST(myx)
replaceKEEPFIRST(myy)

并为您的工作:

big$price.x <- replaceKEEPFIRST(big$price.x)
big$price.y <- replaceKEEPFIRST(big$price.y)
于 2013-01-06T14:23:15.963 回答