我之前提出了一个问题,这个问题已迁移到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
答案 0 :(得分: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值吗?
e.g。
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)