如何将XTS对象的列除以另一XTS对象的列除以R中的列名
我有两个XTS
对象,df1
和df2
以这种方式看,re
spectively:
df1:
|Argentina |Peru |Chile |Colombia |Brasil |
----------------------------------------------------------------
2017-01-01 |4 |12 |16 |8 |32 |
2018-01-01 |14 |18 |6 |4 |82 |
2019-01-01 |64 |22 |14 |18 |52 |
2020-01-01 |24 |80 |36 |6 |14 |
2021-01-01 |34 |70 |36 |60 |74
|
df2:
|Argentina |Colombia |Chile |Peru |Brasil |
----------------------------------------------------------------
2017-01-01 |1 |1 |16 |12 |2 |
2018-01-01 |7 |2 |3 |2 |41 |
2019-01-01 |16 |18 |1 |11 |13 |
2020-01-01 |8 |2 |3 |40 |7 |
2021-01-01 |17 |30 |6 |35 |74 |
我想在df1
中的每一列的每个元素中,在相应列中的同一日期(按国家/地区,IE按列名)中的元素将df2
中的元素划分为同一日期。例如, in
df1
在df1
中将列的每个元素除以“智利”
in in
的日期df2
要获得dataframe df3
:
|Argentina |Peru |Chile |Colombia |Brasil |
----------------------------------------------------------------
2017-01-01 |4 |1 |1 |8 |16 |
2018-01-01 |2 |9 |2 |2 |2 |
2019-01-01 |4 |2 |14 |1 |4 |
2020-01-01 |3 |2 |12 |3 |2 |
2021-01-01 |2 |2 |6 |2 |1 |
我对做df1/df2
进行,但是由于XTS中的列没有相同的顺序,结果我没有任何意义。...你能帮我吗?
I have two xts
objects, df1
and df2
that look this way, re
spectively:
df1:
|Argentina |Peru |Chile |Colombia |Brasil |
----------------------------------------------------------------
2017-01-01 |4 |12 |16 |8 |32 |
2018-01-01 |14 |18 |6 |4 |82 |
2019-01-01 |64 |22 |14 |18 |52 |
2020-01-01 |24 |80 |36 |6 |14 |
2021-01-01 |34 |70 |36 |60 |74
|
df2:
|Argentina |Colombia |Chile |Peru |Brasil |
----------------------------------------------------------------
2017-01-01 |1 |1 |16 |12 |2 |
2018-01-01 |7 |2 |3 |2 |41 |
2019-01-01 |16 |18 |1 |11 |13 |
2020-01-01 |8 |2 |3 |40 |7 |
2021-01-01 |17 |30 |6 |35 |74 |
And I want to divide each element of each column in df1
by the element in the same date in the corresponding column (by country, i.e. by column name) in df2
. For example divide each element of the column "Chile"
in df1
by the corresponding element by date of the column "Chile"
in df2
to obtain the dataframe df3
:
|Argentina |Peru |Chile |Colombia |Brasil |
----------------------------------------------------------------
2017-01-01 |4 |1 |1 |8 |16 |
2018-01-01 |2 |9 |2 |2 |2 |
2019-01-01 |4 |2 |14 |1 |4 |
2020-01-01 |3 |2 |12 |3 |2 |
2021-01-01 |2 |2 |6 |2 |1 |
It occurs to me to do df1/df2
but as the columns in the xts do not have the same order, the result I get does not make sense.... Could you help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
诀窍是通过对列名进行排序并使用它以按顺序选择列来获取数据。这仅在两个XTS对象中的所有列名都相同时才起作用。
注意:我已将DF1和DF2对象重命名为df1_xts和df2_xts,以表明我们正在处理XTS对象而非数据。框架以避免任何混乱。
The trick is to get the data in the same order by sorting the column names and use this to select the columns in order. This only works if all the column names are the same in both xts objects.
Note: I have renamed the df1 and df2 objects to df1_xts and df2_xts to show that we are dealing with xts objects and not data.frames to avoid any confusion.