如何对r中具有相同名称的多行执行值的总和并在plotly中绘制图表。我尝试了几种方法,例如聚合和轻触,它们似乎都不适合我,有人告诉我我要去哪里错了。
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(shiny)
library(plotly)
#> Loading required package: ggplot2
#>
#> Attaching package: 'plotly'
#> The following object is masked from 'package:ggplot2':
#>
#> last_plot
#> The following object is masked from 'package:stats':
#>
#> filter
#> The following object is masked from 'package:graphics':
#>
#> layout
cdata1<-data.frame(stringsAsFactors=FALSE,
names = c("a", "a", "a", "a", "a", "a", "a", "a", "b", "b", "b", "b",
"b", "c", "c", "c", "d", "d", "d"),
values = c(12, 32, 43, 45, 21, 21, 21, 32, 43, 54, 65, 76, 87, 80, 78,
68, 68, 67, 57)
)
ui<-fluidPage(fluidRow(plotlyOutput("id1")),
fluidRow(plotlyOutput("id2"))
)
server<-function(input,output){
output$id1<-renderPlotly({
# a<-aggregate(cdata1$X2014,by=list(cdata1$States.UTs),FUN=sum)
# plot_ly(cdata1,x=cdata1$States.UTs,y=cdata1$X2014)
cdata1 %>%
group_by(grp = rleid(cdata1$names)) %>%
summarise(names = first(cdata1$names),
values = sum(cdata1$values)) %>%
ungroup %>%
select(-grp)
plot_ly(cdata1,x=cdata1$names,y=cdata1$values)
})
}
shinyApp(ui,server)
答案 0 :(得分:1)
这有用吗?
> aggregate(values ~ names, data = cdata1, FUN = sum)
names values
1 a 227
2 b 325
3 c 226
4 d 192
答案 1 :(得分:0)
我不确定下面的代码是否在寻找。否则,@Roman Luštrik对aggreate()
的解决方案可能是您要解决的问题。
data <- within(data, s <- ave(values, names, FUN = sum))
如此
> data
names values s
1 a 12 227
2 a 32 227
3 a 43 227
4 a 45 227
5 a 21 227
6 a 21 227
7 a 21 227
8 a 32 227
9 b 43 325
10 b 54 325
11 b 65 325
12 b 76 325
13 b 87 325
14 c 80 226
15 c 78 226
16 c 68 226
17 d 68 192
18 d 67 192
19 d 57 192
数据
data<-data.frame(stringsAsFactors=FALSE,
names = c("a", "a", "a", "a", "a", "a", "a", "a", "b", "b", "b", "b",
"b", "c", "c", "c", "d", "d", "d"),
values = c(12, 32, 43, 45, 21, 21, 21, 32, 43, 54, 65, 76, 87, 80, 78,
68, 68, 67, 57)
)
答案 2 :(得分:0)
library(dplyr)
cdata1 %>%
group_by(names) %>%
summarise(values = sum(values))
# A tibble: 4 x 2
names values
<chr> <dbl>
1 a 227
2 b 325
3 c 226
4 d 192