修改数据框的列,计算新列。
一. 创建新列
用 dplyr 包中的 mutate() 创建或修改列:
iris %>%
as_tibble(iris) %>%
mutate(new_column = "recycle_me")
若只给新列提供长度为 1 的向量,则循环使用得到值相同的一列;正常是以长度等于行数的向量赋值:
iris %>%
as_tibble(iris) %>%
mutate(new_column = rep_len(month.name, length.out=n()))
注: n() 返回group size, 未分组则为总行数。
二. 计算新列
用数据框的列计算新列,若修改当前列,只需要赋值给原列名。
iris %>%
as_tibble(iris) %>%
mutate(add_all = Sepal.Length + Sepal.Width + Petal.Length + Petal.Width)
注意,不能用sum(), 它会将整个列的内容都加起来,类似的还有 mean().
在同一个 mutate() 中可以