我看了一下类似的问题,但找不到我的答案和我的代码无法工作的原因,我有一个数据帧

# Number of participants, sessions, and session epochs
n_participants <- 5
n_sessions <- 7
n_session_epochs <- 4

# Create the initial data frame
participant_ids <- paste0("ID-", 1:n_participants)
sessions <- 1:n_sessions
session_epochs <- 1:n_session_epochs

# Create a data frame with all combinations of participants, sessions, and session epochs
df <- expand.grid(Participant = participant_ids, 
                  Session = sessions, 
                  Session_Epoch = session_epochs)

# Add F_response with random values
set.seed(123)  # For reproducible results
df$F_response <- sample(1:4, nrow(df), replace = TRUE)

# Function to generate increasing accuracy values
generate_accuracy <- function() {
  start_value <- runif(1, 0, 0.25)
  end_value <- 1
  seq(from = start_value, to = end_value, length.out = n_sessions * n_session_epochs)
}

# Apply the function to each participant and reshape the data
accuracy_values <- replicate(n_participants, generate_accuracy())
df$Accuracy <- as.vector(t(accuracy_values))

# Arrange the data frame by Participant, Session, and Session_Epoch
df <- df %>% arrange(Participant, Session, Session_Epoch)

现在我想创建一个曲线图,其中我只 for each 参与者创建了一个曲线图,其中我只连接了会话中的第一个Session_Epoch,我try 创建一个新的组,但似乎不起作用(我try 的代码如下所示),不确定原因

(a = df %>%
    mutate(grp = if_else(Session_Epoch == 1, Session, NA)) %>%
    ggplot(aes(x = Accuracy, y = F_response)) +
    geom_point(aes(color = as.factor(Session), shape = as.factor(Session_Epoch)), size=3) +
    geom_hline(yintercept = 0,linetype = "dashed", color = "grey") +
    geom_path(aes(group = as.factor(grp))) +
    theme_bw() +
    facet_grid(~Participant) +
    theme(text = element_text(size = 15)))

enter image description here

推荐答案

您可以使用data参数指定要在每个层中使用的数据子集.你不需要mutate路.也就是说(遵循geom_path的文档)..

df %>%
  ggplot(aes(x = Accuracy, y = F_response)) +
  geom_point(aes(color = as.factor(Session), shape = as.factor(Session_Epoch)), size=3) +
  geom_hline(yintercept = 0,linetype = "dashed", color = "grey") +
  geom_path(data=~subset(.x,Session_Epoch==1)) +
  theme_bw() +
  facet_grid(~Participant) +
  theme(text = element_text(size = 15))

enter image description here

您前面的代码在会话epoch 1中 for each 会话创建了不同的因子水平(因此没有分组),但将所有其他会话连接在一起,因为它们的值都为NA

R相关问答推荐

在R中,如何在使用tibble::enFrame % % unlist转换后从收件箱中重组嵌套列表?

替换收件箱的子集(行和列)

feature_weights参数没有影响Xgboost

如何在弹性表中为类别值的背景上色

为什么当我try 在收件箱中使用合并功能时会出现回收错误?

在不安装软件包的情况下测试更新

如何从当前行上方找到符合特定条件的最接近值?

如何在kableextra调用cell_spec()中忽略NA?

将小数分隔符放在R中的前两位数字之后

Select 季度月值

R-按最接近午夜的时间进行筛选

有没有一种方法可以同时对rhandsontable进行排序和从rhandsontable中删除?

如何在PDF格式的kableExtra表格中显示管道字符?

我们如何在R中透视数据并在之后添加计算

使用未知字符数(不受限制的最大长度)的Lookback有什么好的替代方案?

如何使用FormC使简单算术运算得到的数字是正确的?

数值型数据与字符混合时如何进行绑定

如何构建一个for循环来循环处理动物ID?

整理曲线图、曲线图和点图

R预测包如何处理ARIMA(Auto.arima函数)中的缺失值