我即将绘制出我想要的图,但还没有完全弄清楚是否stat_summary是显示所需图的正确方法。
所需的输出是每个类别内每年具有中线的散点图。例如,在下图中,我想要 A 类中的 1999 年、2000 年和 2001 年的值有一条中线(即按颜色划分的 3 条线),然后 B 类中的值也有一条中线(因此总共 6 条中线)。
我看了这里,但这似乎没有达到我想要的,因为它使用的是方面。
我的图看起来像是在每个类别的中位数之间画一条线。可以stat_summary只在每个类别内绘制一条中线,还是需要使用不同的方法(例如计算中位数并按类别将每条线添加到图中?
可重现的简单示例
library(tidyverse)
library(lubridate)
# Sample data
Date <- sort(sample(seq(as.Date("1999-01-01"), as.Date("2002-01-01"), by = "day"), 500))
Category <- rep(c("A", "B"), 250)
Value <- sample(100:500, 500, replace = TRUE)
# Create data frame
mydata <- data.frame(Date, Category, Value)
# Plot by category and color by year
p <- ggplot(mydata, aes(x = Category, y = Value,
color = …Run Code Online (Sandbox Code Playgroud) 一个快速的问题,希望能快速回答。
我试图仅在具有数字数据的列上使用 rowSums。我想做一些与此等效的事情(使用内置数据集 CO2 作为可重现的示例):
# Reproducible example
CO2 %>%
mutate( Total = rowSums(.[c(-1, -2, -3)]) ) %>%
head()
Plant Type Treatment conc uptake Total
1 Qn1 Quebec nonchilled 95 16.0 111.0
2 Qn1 Quebec nonchilled 175 30.4 205.4
3 Qn1 Quebec nonchilled 250 34.8 284.8
4 Qn1 Quebec nonchilled 350 37.2 387.2
5 Qn1 Quebec nonchilled 500 35.3 535.3
6 Qn1 Quebec nonchilled 675 39.2 714.2
Run Code Online (Sandbox Code Playgroud)
我用 mutate 和 is.numeric 尝试了 rowSums,但没有成功。是否有捷径可寻?
# How do sum rows using is.numeric …Run Code Online (Sandbox Code Playgroud) 我试图摆脱R中的循环,并期待矢量化和加速我的代码的一部分.
可重复的例子:
library(dplyr)
# This works using a For loop -----------------------------------
# create sample data frame
df <- data.frame(Date = rep(c("Jan1", "Jan2", "Jan3"), 3),
Item = c(rep("A", 3), rep("B", 3), rep("C", 3)),
Value = 10:18)
diff <- numeric() # initialize
# Loop through each item and take difference of latest value from earlier values
for (myitem in unique(df$Item)) {
y = df[df$Date == last(df$Date) & df$Item == myitem, "Value"] # Latest value for an item
x = df[df$Item == …Run Code Online (Sandbox Code Playgroud)