有没有办法使用dpylr 的重新编码功能和查找表(data.frame或list)?
我想拥有的东西会是这样的:
# Recode values with list of named arguments
data <- sample(c("a", "b", "c", "d"), 10, replace = T)
lookup <- list(a = "Apple", b = "Pear")
dplyr::recode(data, lookup)
Run Code Online (Sandbox Code Playgroud)
我发现mapvalues和重估从功能上plyr包.为解释将它们组合在一起可以在这里.但是,我想知道只有dplyr才能实现类似的功能.
使用dplyr,我想计算所有列的行总和.我设法通过使用列索引来做到这一点.但是,我想使用列名而不是列索引.我怎样才能做到这一点?
示例数据:
# Using dplyr 0.5.0
library(tidyverse)
# Create example data
`UrbanRural` <- c("rural", "urban")
type1 <- c(1582, 671)
type2 <- c(5247, 4123)
type3 <- c(87, 65)
df <- data.frame(`UrbanRural`, type1, type2, type3)
df <- tbl_df(df)
Run Code Online (Sandbox Code Playgroud)
# A tibble: 2 x 5
UrbanRural type1 type2 type3 tot
<fctr> <dbl> <dbl> <dbl> <dbl>
1 rural 1582 5247 87 6916
2 urban 671 4123 65 4859
Run Code Online (Sandbox Code Playgroud)
有效的示例(使用列索引):
df %>% mutate(tot = rowSums(.[-1]))
Run Code Online (Sandbox Code Playgroud)
# A tibble: 2 x 5
UrbanRural type1 …
Run Code Online (Sandbox Code Playgroud) 我想应用dplyr函数summarise_all来计算每列中的平均值.但是,我确实想省略0值,因此需要构建条件语句.
df <- data.frame(x = c(1,0,4,6,0,9), y = c(12,42,8,0,11,2))
df %>% summarise(mean)
Run Code Online (Sandbox Code Playgroud)
这里解释了在为每个单独的列定义聚合功能时如何做.但是,我想使用summarise_all,因为我的originla数据包含许多列.
我想使用 ggplot2 在堆叠条形图中的不同元素之间画线。我已经使用 ggplot2(第一个图)绘制了一个堆叠条形图,但想要得到类似于第二个图的东西。
dta <- tribble(
~colA, ~colB, ~colC,
"A", "a", 1,
"A", "b", 3,
"B", "a", 4,
"B", "b", 2); dta
ggplot(dta, aes(x = colA, y = colC, fill = colB)) +
geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
禁食方式可能会通过手动将线条绘制到导出的图像中来添加线条。但是,我更喜欢避免这种情况。
这个Stackoverflow 条目(特别是Henrik的回答)给出了一个潜在的解决方案。但是,我想知道是否有另一种更通用的解决方案(即不需要手动定义线段/线的所有起点和终点)