问题描述
我需要将两个列表互相合并,但是我没有得到想要的东西,我认为这是因为"Date"
列采用两种不同的格式。我有一个名为li
的列表,该列表中有12个列表,每个列表具有以下格式:
> tail(li$fxe)
Date fxe
3351 2020-06-22 0.0058722768
3352 2020-06-23 0.0044256216
3353 2020-06-24 -0.0044998220
3354 2020-06-25 -0.0027309539
3355 2020-06-26 0.0002832672
3356 2020-06-29 0.0007552346
我正在尝试将每个唯一列表与名为factors
的另一个列表合并,该列表看起来像:
> tail(factors)
Date Mkt-RF SMB HML RF
3351 20200622 0.0071 0.83 -1.42 0.000
3352 20200623 0.0042 0.15 -0.56 0.000
3353 20200624 -0.0261 -0.52 -1.28 0.000
3354 20200625 0.0112 0.25 0.50 0.000
3355 20200626 -0.0243 0.16 -1.37 0.000
3356 20200629 0.0151 1.25 1.80 0.000
之所以需要这种结构,是因为我试图将它们发送给我编写的用于进行线性回归的函数。但是我函数的第一行旨在合并这些列表。当我合并它们时,我什至以为我的列表显然具有相同数量的行,但最终得到的是空结构。在我的函数中,df
是li
。 li
的嵌入列表使我感到困惑。有人可以帮忙吗?
我要使用的功能:
Bf <- function(df,fac){
#This function calculates the beta of the french fama factor #using linear regression
#Input: df = a dataframe containg returns of the security
# fac = dataframe containing excess market retrun and
# french fama 3 factor
#Output: a Beta vectors of the french fama model
temp <- merge(df,fac,by="Date")
temp <- temp[,!names(temp) %in% "Date"]
temp[,1] <- temp[,1] - temp$RF return(lm(temp[,1]~temp[,2]+temp[,3]+temp[,4])$coeff)
}
解决方法
a:您正在处理数据框而不是列表 b:如果要合并它们,则需要修改factor $ date列以匹配li $ fxe $ date
尝试做:
factors$date <- as.Date(strptime(factors$date,format = "%Y%M%d"))
这应将“因素”列转换为“日期”格式。