在R转换为数据框时在R中缺少行名

时间:2018-07-25 14:34:39

标签: r dataframe plotly r-plotly

我有一个矩阵,试图将其转换为数据框,然后使用它使用plotly绘制轨迹。下面是矩阵:

                  [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]     [,9]     [,10]    [,11]   
Month_considered  "Apr-17" "May-17" "Jun-17" "Jul-17" "Aug-17" "Sep-17" "Oct-17" "Nov-17" "Dec-17" "Jan-18" "2/1/18"
Exclusive Loyal   "15695"  "17782"  "18523"  "18291"  "19949"  "18668"  "17621"  "17589"  "19085"  "18618"  "17745" 
Interacting Loyal "3649"   "4073"   "4453"   "4367"   "4683"   "4515"   "4294"   "4174"   "4381"   "4319"   "4412"  
Switcher          "518"    "674"    "814"    "905"    "946"    "757"    "791"    "908"    "841"    "541"    "332"   
Total             "19862"  "22529"  "23790"  "23563"  "25578"  "23940"  "22706"  "22671"  "24307"  "23478"  "22489" 

当我将其转换为数据框并转换第一行时,因为缺少行名Month_Considered。下面是我将其更改为数据框并添加列名的方法。

atc_seg_master <- as.data.frame(atc_seg_table)
names(atc_seg_master) <- as.matrix(atc_seg_master[1, ])
atc_seg_master <- atc_seg_master[-1, ]
atc_seg_master

结果是,当我尝试使用绘图方式绘制轨迹时,出现错误Month_Considered丢失。

p <- plot_ly(atc_seg_master, x = ~ Month_considered, type = 'scatter',mode = 'line+markers',line = list(color = 'rgb(205, 12, 24)', width = 4))

for(trace in colNames){
  p <- p %>% plotly::add_trace(y = as.formula(paste0("~`", trace, "`")), name = trace)
}

p %>%
  layout(title = "Trend Over Time",
         xaxis = list(title = ""),
         yaxis = list (title = "Monthly Count of Products Sold"))
p

如何将第一行名称命名为Month_Considered,以便于绘制轨迹。

0 个答案:

没有答案