在这里自学编程,没有 cs 背景。似乎我一直遇到这样的问题,我不明白我使用的 tidy verse 函数在幕后发生了什么。我需要有人解释为什么这不能以我能理解的方式工作。
我正在尝试运行此代码:
df2.p<- df2 %>% mutate(across(4:9,~./weight))
我理解这段代码的意思是“将 df2 的 4:9 列除以同样在 df2 中的名为 weight 的列”
我收到此错误:
<块引用>错误:mutate()
输入 ..1
有问题。
x 输入 ..1
无法回收到大小为 52。
ℹ 输入..1
是(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...
。
ℹ 输入 ..1
的大小必须为 52 或 1,而不是 42021。
我查看了 df2 的大小。不知道发生了什么。
class(df2) "tbl_df" "tbl" "data.frame" 暗淡(df2)是 52 x 10
创建 df2 的代码是:
df2<- df1.w %>%
group_by(state) %>%
summarise(weight.s= sum(weight, na.rm= TRUE),
native.s= sum(Native, na.rm= TRUE),
asian.s= sum(Asian, na.rm= TRUE),
black.s= sum(Black, na.rm= TRUE),
pacisland.s= sum(`Pacific Islander`, na.rm= TRUE),
middle.s= sum(`Middle Eastern`, na.rm= TRUE),
white.s= sum(White, na.rm= TRUE),
raceo.s= sum(`Race Other`, na.rm= TRUE),
na.rm= TRUE
)
我从一个有 42021 行的 df1.w 创建了 df2。我按州将这些行分组到 52 行。似乎 mutate() 正在取消分组 df2 并将其视为 df1.w 不知何故。我如何让它发挥作用?
答案 0 :(得分:0)
在 OP 的帖子中,summarise
没有对 'weight' 执行 sum
,因此该列不存在于输出 'df2' 中,因为 summarise
只返回汇总列和分组列。我们可以使用 across
和 everything
对所有列执行 sum
,然后执行 mutate
library(dplyr)
df1.w %>%
group_by(state) %>%
summarise(across(everything(), sum, na.rm= TRUE)) %>%
mutate(across(4:9,~./weight))
发生错误的原因可能是作为对象的“权重”可能是在全局环境中作为原始对象的一部分创建的