所以我有两个名称和日期完全相同的数据表,例如表a在那个月有最低点:
Date companya companyb companyc ...company200
2019-01 7 5 3 ...
2019-02 4 4 1 ...
表b有当月的最高点:
Date companya companyb companyc ...company200
2019-01 10 15 20 ...
2019-02 5 10 40 ...
我想找到从表a到表b的%变化,我尝试使用库quantmod:中的Delt
change<-bind_rows(a,b)%>%
group_by(Date) %>%
summarise_each(funs(delt(.))) %>%
data.frame()
但这给了我一排NA和绝对的变化:
Date companya companyb companyc ...company200
2019-01 NA NA NA NA
2019-01 .42 2 5.6 x
2019-02 NA NA NA NA
2019-02 0 1.5 39 x
我如何找到算术变化,使其看起来像:
Date companya companyb companyc ...company200
2019-01 -.42 -2 -5.6 x
2019-02 0 -1.5 -39 x
谢谢你的帮助!我真的很感激!!
*如果有人有同样的问题,请查看Duck的解决方案,它很有效!***
为了提供更多信息,我的最终目标是在末尾的另一列中加入指数的百分比变化(我也有指数的高点和低点,需要找到变化(,并进行比较:我的索引如下:
Data Index
2019-01 -2.5
2019-02 -5
etc etc
我想加入左翼,所以
df4<-merge(df3,index, by="Date")
所以它应该是这样的:
Date companya companyb companyc ...company200 index
2019-01 -.42 -2 -5.6 x -2.5
2019-02 0 -1.5 -39 x -5
etc etc etc etc etc etc
我的目标是通过查看每家公司的百分比变化是否比指数高出-20%来标记每一列,我想的是这样的:
Flags <-df5 %>%group_by(date)
%>% transmute ((diff(col(2:200)-index)>20~1,
diff(col(2:200)-index)=<20~0)
所以它看起来像:
Date companya companyb companyc ...company200 index
2019-01 0 0 0 x -2.5
2019-02 0 0 1 x -5
etc
请让我知道我的逻辑是否正确!
使用从您的帖子中获取的下一个数据,您可以获得变体:
#Data
df1 <- structure(list(Date = structure(1:2, .Label = c("2019-01", "2019-02"
), class = "factor"), companya = c(7L, 4L), companyb = 5:4, companyc = c(3L,
1L)), class = "data.frame", row.names = c(NA, -2L))
df2 <- structure(list(Date = structure(1:2, .Label = c("2019-01", "2019-02"
), class = "factor"), companya = c(10L, 5L), companyb = c(15L,
10L), companyc = c(20L, 40L)), class = "data.frame", row.names = c(NA,
-2L))
#Code
df3 <- as.data.frame(cbind(df1[,1,drop=F],(df1[,-1]-df2[,-1])/df1[,-1]))
Date companya companyb companyc
1 2019-01 -0.4285714 -2.0 -5.666667
2 2019-02 -0.2500000 -1.5 -39.000000
我不清楚你是如何获得index
的,如果你解释得更多,我可以更新答案。
我不确定我是否正确理解了这个问题。但据我所知,您正在尝试对数据帧进行算术运算,然后尝试将另一列加入其中进行比较。以下是我认为可以使用测试数据集进行的操作。
这两个数据帧是a和b,index是用于比较的索引数据,c则是生成的数据帧。
Date <- seq(as.Date("2020-01-01"), length.out = 100, by= "day")
a <- data.frame(Date, CompanyA= 1:10, CompanyB= 11:20, CompanyC= 21:30)
b <- data.frame(Date, CompanyA= 101:110, CompanyB= 111:120, CompanyC= 121:130)
index <- rnorm(100, mean = 10, sd=1)
c <- data.frame(a$Date, (a[,-1]-b[,-1])*100/a[,-1], index)