问题
I have two data frames and I need to put the line of my second data frame as the last line of my first data frame:
The first data frame is PETR3.SA:
tail(PETR3.SA)
PETR3.SA.Open PETR3.SA.High PETR3.SA.Low PETR3.SA.Close
2020-04-23 17.35522 17.63133 16.85232 17.09884
2020-04-24 16.86218 17.01009 15.30415 15.84650
2020-04-27 16.14233 16.68468 15.74789 16.56635
2020-04-28 17.49000 18.02000 17.11000 18.02000
2020-04-29 18.51000 19.30000 18.35000 19.00000
2020-04-30 18.73000 19.18000 18.43000 18.65000
PETR3.SA.Volume PETR3.SA.Adjusted
2020-04-23 19498900 17.09884
2020-04-24 39716700 15.84650
2020-04-27 25446600 16.56635
2020-04-28 24004700 18.02000
2020-04-29 26938000 19.00000
2020-04-30 23209200 18.65000
str(PETR3.SA)
An ‘xts’ object on 2015-01-02/2020-04-30 containing:
Data: num [1:1322, 1:6] 9.07 8.18 7.84 7.86 8.15 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:6] "PETR3.SA.Open" "PETR3.SA.High" "PETR3.SA.Low" "PETR3.SA.Close" ...
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 3
$ src : chr "yahoo"
$ updated : POSIXct[1:1], format: "2020-05-04 17:14:02"
$ na.action: 'omit' int [1:3] 779 1038 1281
..- attr(*, "index")= num [1:3] 1.52e+09 1.55e+09 1.58e+09
My second df:
cotacao_xts
PETR3.SA.Open PETR3.SA.High PETR3.SA.Low PETR3.SA.Close
2020-05-04 19.02 19.02 19.02 19.02
PETR3.SA.Volume PETR3.SA.Adjusted
2020-05-04 0 19.02
> str(cotacao_xts)
An ‘xts’ object on 2020-05-04/2020-05-04 containing:
Data: num [1, 1:6] 19 19 19 19 0 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:6] "PETR3.SA.Open" "PETR3.SA.High" "PETR3.SA.Low" "PETR3.SA.Close" ...
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
NULL
I need to put my second df (cotacao_xts) as the last line of my first df.
I tried bind_rows, but this is what I got:
> new_df <- PETR3.SA %>%
+ bind_rows(cotacao_xts)
Error: Argument 1 must have names
回答1:
As these are xts
objects, we can use rbind
assuming the index are unique
library(xts)
rbind(PETR3.SA, cotacao_xts)
methods(class = 'xts')[50]
#[1] "rbind.xts"
According to ?bind_rows
... - Data frames to combine
It can be data.table
, data.frame
or tbl_df
. The xts
object is neither one of those. It is a matrix
with xts
attribute. If we need to use bind_rows
, then the objects needs to be converted to data.frame
来源:https://stackoverflow.com/questions/61598725/problem-with-bind-rows-error-argument-1-must-have-names