【问题标题】:How to cbind unequal length columns in r, matching the length of the shortest and accounting for date differences?如何在 r 中绑定长度不等的列,匹配最短的长度并考虑日期差异?
【发布时间】:2018-03-31 19:21:37
【问题描述】:

问题:

我正在尝试将具有不同长度和起始日期(想想股票价格)的两个向量的列组合起来,并希望在匹配最短的长度的同时从最长的向量中截断多余的列。任何帮助将不胜感激!

到目前为止我所尝试的:

combinedcolumns<-cbind(A$Col,B$Col[(length(B$Col)-length(A$Col)):length(B$Col)])

结果:

我能够绑定两列并为 A 获得正确的值,但我在整个组合列的长度上为 B 获得相同的值。

提前致谢!

【问题讨论】:

  • 较短列中的所有日期在较长列中是否都有匹配的日期?如果是这样,最好按日期merge。例如,假设A 是较短的一个,并且两个数据框都有一个名为date 的列:merge(A, B, by="date", all.x=TRUE)

标签: r cbind


【解决方案1】:

一种方法是通过用NAs(或其他任何东西)填充较短的列来扩展较短的列,即

lmax <- max(c(length(A$col1), length(B$col2))) # determining which column is longer / shorter
lmin <- max(c(length(A$col1), length(B$col2)))
col2change <- which(c(length(A$col1), length(B$col2)) == lmin)
newcol <- rep(NA, lmax) # creating a vector of length lmax filled with NAs
newcol[1:lmin] <- ifelse(col2change == 1,          # adding the data of the shorter col
                         A$col1,
                         B$col2)
combinedcolumns <- ifelse(col2change == 1,
                         cbind(A$col1, newcol),
                         cbind(newcol, B$col2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 2023-03-23
    • 2021-10-28
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多