R:将缺少值的列添加到数据框 [英] R : add a column with missing values to a dataframe

查看:142
本文介绍了R:将缺少值的列添加到数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用财务数据,我的主数据框的行名是日期。

 >资产[1:3,1:5] 
ALD SFN TCO KIM CTX
2003-01-03 48.1 23.98 23.5 23 22.34
2003-01-06 48.1 23.98 23.5 23 22.34
2003-01-07 48.1 23.98 23.5 23 22.34

我想添加一列(这里我想要从相同类型的数据框中添加FOC $,但是某些日期缺少:

 > FOC [1:3,1:2] 
关闭Adj.Close
2003-01-03 510 510
2003-01-07 518 518

缺少的值应该是NA,所以它看起来像这样:

 >资产[1:3,1:6] 
ALD SFN TCO KIM CTX FOC
2003-01-03 48.1 23.98 23.5 23 22.34 510
2003-01-06 48.1 23.98 23.5 23 22.34 NA
2003-01-07 48.1 23.98 23.5 23 22.34 518

有没有一个很好的方法去做?我通过执行类似于

 > rowtoadd<  -  list(ALD = 18.1,...)
> dataframe [nrow(dataframe)+ 1,names(rowtoadd)]< - rowtoadd

解决方案

您可以使用合并方法。



我想你正在使用xts时间序列对象。这些将自动处理行名。从 help(merge.xts),有一个关键字参数 join 可以用来控制合并的发生。它默认为外部。示例:

  dat = merge(assets [1:3,],FOC [,1:2],join ='left ')
> dat
ALD SFN TCO KIM CTX关闭Adj.Close
2003-01-03 48.1 23.98 23.5 23 22.34 510 510
2003-01-06 48.1 23.98 23.5 23 22.34 NA NA
2003-01-07 48.1 23.98 23.5 23 22.34 518 518


I am using financial data and the row names of my main dataframe are dates.

   > assets[1:3,1:5]
            ALD   SFN  TCO KIM   CTX
2003-01-03 48.1 23.98 23.5  23 22.34
2003-01-06 48.1 23.98 23.5  23 22.34
2003-01-07 48.1 23.98 23.5  23 22.34

I would like to add a column (here I want to add FOC$close to assets) from a dataframe that is of same type but some dates are missing :

   > FOC[1:3,1:2]
           Close Adj.Close
2003-01-03   510       510
2003-01-07   518       518

The missing values should just be NA's, so it would look like that :

   > assets[1:3,1:6]
            ALD   SFN  TCO KIM   CTX FOC
2003-01-03 48.1 23.98 23.5  23 22.34 510
2003-01-06 48.1 23.98 23.5  23 22.34 NA
2003-01-07 48.1 23.98 23.5  23 22.34 518

Is there a nice way to do that? I managed to do something similar with rows by doing something like

> rowtoadd <- list(ALD=18.1,...)
> dataframe[nrow(dataframe) + 1, names(rowtoadd)] <- rowtoadd

but I am not able to do this for columns.

解决方案

You can use the merge method.

I think you are using xts time-series objects. These handle the row names automatically. From help(merge.xts), there is a keyword argument join that you can use to control how the merge occurs. It defaults to 'outer'. Example:

dat = merge(assets[1:3,], FOC[,1:2], join='left')
> dat
            ALD   SFN  TCO KIM   CTX Close Adj.Close
2003-01-03 48.1 23.98 23.5  23 22.34   510       510
2003-01-06 48.1 23.98 23.5  23 22.34    NA        NA
2003-01-07 48.1 23.98 23.5  23 22.34   518       518

这篇关于R:将缺少值的列添加到数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆