R:添加一个长度较短的列,在单个列中减去每一行,即第1-2行、第2-3行
我有一个数据帧,看起来像这个sx16数据帧: 如果链接不起作用: 数据帧称为sx16 它有列名: 日期、未平仓、高位、低位、结算 我想添加一个名为up_period的列,如果下面的计算为正,则该列将打印1,如果下面的计算为负,则打印0:R:添加一个长度较短的列,在单个列中减去每一行,即第1-2行、第2-3行,r,R,我有一个数据帧,看起来像这个sx16数据帧: 如果链接不起作用: 数据帧称为sx16 它有列名: 日期、未平仓、高位、低位、结算 我想添加一个名为up_period的列,如果下面的计算为正,则该列将打印1,如果下面的计算为负,则打印0: sx16$Settle[ 1: nrow(sx16)] - sx16$Settle[ 2: nrow(sx16)] 当然,这会产生一个错误,因为新列表比原始的sx16短 我试着用rbind.fill这样包裹它: sx16$up_period <- rb
sx16$Settle[ 1: nrow(sx16)] - sx16$Settle[ 2: nrow(sx16)]
当然,这会产生一个错误,因为新列表比原始的sx16短
我试着用rbind.fill这样包裹它:
sx16$up_period <- rbind.fill(sx16$Settle[ 1: nrow(sx16)] - sx16$Settle[ 2: nrow(sx16)])
sx16$up\u period我将使用iris数据集:
x <- iris
dummy <- x$Sepal.Length #repeat column again but rename dummy
dummy[length(dummy)+1]=0 #add a value of 0 to the end for the day thats not happened yet
dummy <- dummy[2:length(dummy)] #translate the column to match the original for calculation
x <- cbind(x,dummy) #add the column to the data
x$up <- x$Sepal.Length-x$dummy #new calculated column
x$dummy <- NULL #remove dummy
x尝试此操作(未定义最后一个上升周期):
sx16$up\u period您可以从dplyr
软件包中使用lead
:
library(dplyr)
result <- sx16 %>% mutate(up_period=as.numeric((Settle-lead(Settle,default=NA)) > 0))
## Date Open High Low Settle up_period
##1 2016-09-30 950.00 958.50 943.00 954.00 1
##2 2016-09-29 947.00 957.25 946.00 950.25 1
##3 2016-09-28 951.75 955.75 944.50 945.50 0
##4 2016-09-27 946.75 953.50 934.00 952.50 1
##5 2016-09-26 951.50 960.25 943.75 945.25 0
##6 2016-09-23 975.00 976.25 952.50 955.00 NA
我很惊讶还没有人提到diffdiff(sx16$Settle)
相当于sx16$Settle[2:nrow(sx16)]-sx16$Settle[1:(nrow(sx16)-1)]
。因此,以下内容适用于您:
sx16$up_period <- c(ifelse(diff(sx16$Settle)<0, 1, 0), NA)
sx16$up\u欢迎来到SO。请读取并使用样本数据:iris$Sepal。长度[1:(nrow(iris)-1]-iris$Sepal。长度[2:nrow(iris)]将处理除最后一个之外的所有值one@OliPaul他们将如何将其绑定到数据帧?它少了一排。另外,所有的符号都是相反的(试试iris$Sepal.Length-c(NA,iris$Sepal.Length[1:nrow(iris)-1])
)你的意思是不是iris$Sepal.Length-c(iris$Sepal.Length[2:nrow(iris)],NA)
这工作得很好。“NA”部分是我不理解的。非常感谢!最后一个元素不适用于滞后序列,NA需要保持序列长度不变。这是一个很好的解决方案。我认为dplyr可能是我的解决方案,但我对它不太熟悉。我必须纠正这一点。as.numeric是if-else的优雅解决方案。谢谢。我试着使用diff,但遇到了一些问题。主要的一点是,它计算的变化是错误的,因为它显示了从第一行到第二行+7的变化,而不是相反。你的解决方案显然是完美无瑕的,所以我不确定我做错了什么。我得回去看看。非常感谢。
sx16 <- structure(list(Date = structure(c(17074, 17073, 17072, 17071,
17070, 17067), class = "Date"), Open = c(950, 947, 951.75, 946.75,
951.5, 975), High = c(958.5, 957.25, 955.75, 953.5, 960.25, 976.25
), Low = c(943, 946, 944.5, 934, 943.75, 952.5), Settle = c(954,
950.25, 945.5, 952.5, 945.25, 955)), .Names = c("Date", "Open",
"High", "Low", "Settle"), row.names = c(NA, -6L), class = "data.frame")
sx16$up_period <- c(ifelse(diff(sx16$Settle)<0, 1, 0), NA)