【发布时间】:2020-01-16 15:06:53
【问题描述】:
这是我第一次发帖,请多多包涵。我正在尝试通过基于现有数据添加新列来操作 R 中的数据集。我已将数据转换为数据框并使用了 mutate 函数。该功能有效。但是,当我再次调用我的数据集以查看更改时,新列消失了。我做错了什么?
# Converting raw data into a tibble data frame for easier data analysis:
spdata <- as_tibble(rawdata)
# Creating a new Grade column based on Math Scores
spdata %>%
mutate(math.grade = case_when(math.score < 60 ~ "F",
math.score >= 60 & math.score <= 69 ~ "D",
math.score >= 70 & math.score <= 79 ~ "C",
math.score >= 80 & math.score <= 89 ~ "B",
math.score >= 90 & math.score <= 100 ~ "A"))
这是我运行 mutate 函数后自动生成的输出:
# A tibble: 1,000 x 9
gender race.ethnicity parental.level.of.education lunch test.preparation.course math.score reading.score writing.score math.grade
<fct> <fct> <fct> <fct> <fct> <int> <int> <int> <chr>
1 female group B bachelor's degree standard none 72 72 74 C
2 female group C some college standard completed 69 90 88 D
3 female group B master's degree standard none 90 95 93 A
4 male group A associate's degree free/reduced none 47 57 44 F
5 male group C some college standard none 76 78 75 C
6 female group B associate's degree standard none 71 83 78 C
7 female group B some college standard completed 88 95 92 B
8 male group B some college free/reduced none 40 43 39 F
9 male group D high school free/reduced completed 64 64 67 D
10 female group B high school free/reduced none 38 60 50 F
# ... with 990 more rows
我的新 math.grade 变量按预期显示。
但是,当我再次调用 spdata 查看时,math.grade 列不见了:
# A tibble: 1,000 x 8
gender race.ethnicity parental.level.of.education lunch test.preparation.course math.score reading.score writing.score
<fct> <fct> <fct> <fct> <fct> <int> <int> <int>
1 female group B bachelor's degree standard none 72 72 74
2 female group C some college standard completed 69 90 88
3 female group B master's degree standard none 90 95 93
4 male group A associate's degree free/reduced none 47 57 44
5 male group C some college standard none 76 78 75
6 female group B associate's degree standard none 71 83 78
7 female group B some college standard completed 88 95 92
8 male group B some college free/reduced none 40 43 39
9 male group D high school free/reduced completed 64 64 67
10 female group B high school free/reduced none 38 60 50
# ... with 990 more rows
【问题讨论】:
-
"dplyr 函数从不修改其输入,因此如果要保存结果,则需要使用赋值运算符 r4ds.had.co.nz/transform.html 在你的情况下,这看起来像
spdata <- spdata %>%.... [the rest] -
可以使用
magrittrtee(它也是命名管道)(magrittr::%%`)进行就地分配。