Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何创建以第一行和第一列为标题的表?_R - Fatal编程技术网

R 如何创建以第一行和第一列为标题的表?

R 如何创建以第一行和第一列为标题的表?,r,R,我想用我已经获得的一些数据在R中创建一个数据表。但是,我不知道如何将这些数据放入表格中,因为这需要一些技巧才能将返回的数据,monthlyRet,分别按月份放入表格中。下图是我想要的表格格式,里面的数据也需要包括在内 请注意,由于getSymbols中的起始日期,正的数量和负的数量的数据从Aug开始,而不是Jan。因此,我希望可以在从Jan到Dec创建的表格中安排No.of.Positive和No.of.Negative,如下图所示 下面的代码是我获取数据的方式 library(quantmod

我想用我已经获得的一些数据在R中创建一个数据表。但是,我不知道如何将这些数据放入表格中,因为这需要一些技巧才能将返回的数据,
monthlyRet
,分别按月份放入表格中。下图是我想要的表格格式,里面的数据也需要包括在内

请注意,由于
getSymbols
中的起始日期,正的
数量和负的
数量的数据从
Aug
开始,而不是
Jan
。因此,我希望可以在从
Jan
Dec
创建的表格中安排
No.of.Positive
No.of.Negative
,如下图所示

下面的代码是我获取数据的方式

library(quantmod)

prices <- 
  getSymbols("^NDX", src = 'yahoo', from = "2009-07-01", to = "2019-08-01", 
             periodicity = "monthly", auto.assign = FALSE, warnings = FALSE)[,4]

return <- diff(log(prices))
r <- na.omit(exp(return)-1)

monthlyRet <- as.numeric(r)

meanMonthlyRet <- c()
No.of.Positive <- c()
No.of.Negative <- c()
for (j in 1:12){
  Group <- c()
  count_pos=0
  count_neg=0
  for (i in seq(j,length(monthlyRet),12)){
    Group[i] <- monthlyRet[i]
    if(monthlyRet[i]>0){
      count_pos <- count_pos+1
    }
    else  if(monthlyRet[i]<0){
      count_neg <- count_neg+1
    }
  }
  meanMonthlyRet[j] <- mean(Group, na.rm=TRUE)
  Positive=0
  Negative=0
  if(meanMonthlyRet[j]>0){
    Positive=count_pos
    Negative=10-Positive
  }
  else if (meanMonthlyRet[j]<0){
    Negative=count_neg
    Positive=10-Negative
  }
  No.of.Positive[j] <- Positive
  No.of.Negative[j] <- Negative
}

# My data required in table #--------------------------------------------------

Year <- c(2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019)
Month <- c("Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul")
r
No.of.Positive
No.of.Negative
库(quantmod)

价格这里有一个简单的解决方案

库(quantmod)
图书馆(tidyverse)
价格%
差异%>%
exp%>%
{. - 1}
表3.1-1%
as.data.frame()%>%
行名称到列()%>%
设置名称(c(“日期”、“变量”))%>%
变异(变量=(变量*100)%%>%round(2))%%>%
单独(日期,c(“年”、“月”、“日”))%>%
选择(-day)%%>%
差价(月,可变)
n_位置0,na.rm=T)
n_负%
rbind(正位,负位)

x这是否仅用于报告目的?然后你可以使用kableExtra,flextable,etcYa,用于报告目的,但我没有时间再次开始学习这两个软件包。感谢你的解决方案,它对我有用!然而,在我运行代码之后,我意识到Jan的正数和负数分别是8和2,而不是6和4。8和2是2月份的数据,似乎每个月的数据提前一个月。我应该如何调整?谢谢你的帮助!:)此外,如果可能的话,我希望收益率数据后面可以有一个“%”,并且表中显示的正/负数字将没有小数点。谢谢我在编辑代码时出错,导致了号码不对的问题。我已经编辑了它,还包括了您第二条评论中的更改。顺便问一下,您对如何将代码中的
NDX.Close
更改为更通用的代码有何建议,以便下次我在
getSymbols
中更改股票代码时,无需再次手动更改
NDX.Close
。谢谢您可以使用
set\u names()