帮我修改以下代码,使他们可以正确运行:scores <- dplyr::data_frame( person = rep(c("A", "B", "C"), each = 2), time = rep(c("pre", "post"), 3), class1 = round(rnorm(6, mean = 80, sd = 4), 0), class2 = round(jitter(class1, 15), 0) ) scores_1 <- scores %>% pivot_longer(cols = c("class1", "class2"), names_to = "class", values_to = "score") scores_2 <- scores %>% spread(key = time, value = class1:class2) scores_3 <- scores_1 %>% group_by(person, class) %>% mutate(diff = score[time == "post"] - score[time == "pre"]) %>% ungroup() scores_3 %>% ggplot(aes(x = class, y = score, color = ifelse(diff >= 0, "green", "red"), shape = person)) + geom_point(size = 3) + labs(x = "Class", y = "Score", color = "Score change", shape = "Person") + theme_classic()
时间: 2024-03-14 19:47:29 浏览: 52
我的代码数据结构求修改
您好,这段代码的问题在于 `data_frame()` 函数已经被弃用,应该使用 `tibble()` 函数来创建数据框。同时,`spread()` 函数也已经被弃用,应该使用 `pivot_wider()` 函数来进行数据透视。下面是修改后的代码:
```
library(tidyverse)
scores <- tibble(
person = rep(c("A", "B", "C"), each = 2),
time = rep(c("pre", "post"), 3),
class1 = round(rnorm(6, mean = 80, sd = 4), 0),
class2 = round(jitter(class1, 15), 0)
)
scores_1 <- scores %>%
pivot_longer(cols = c("class1", "class2"), names_to = "class", values_to = "score")
scores_2 <- scores %>%
pivot_wider(names_from = time, values_from = c(class1, class2), names_sep = "_")
scores_3 <- scores_1 %>%
group_by(person, class) %>%
mutate(diff = score[time == "post"] - score[time == "pre"]) %>%
ungroup()
scores_3 %>%
ggplot(aes(x = class, y = score, color = ifelse(diff >= 0, "green", "red"), shape = person)) +
geom_point(size = 3) +
labs(x = "Class", y = "Score", color = "Score change", shape = "Person") +
theme_classic()
```
这样,代码就可以正确运行了。
阅读全文