我有一个名为counts的数据框,一个列名称称为merged $ year。当我应用代码时
counts %>%
group_by(counts$merged$year) %>%
mutate(C= sum(V1))
到此数据框,它始终显示
Error: Unsupported type NILSXP for column "counts$merged$year"
我尝试更改列的名称,因此代码变为
counts %>%
group_by(counts$merged1gwmd, counts$merged1year) %>%
mutate(C= sum(V1))
但我仍然有错误:
Error: invalid subscript type 'double'
答案 0 :(得分:1)
我们可以使用反引号来选择这些列,但不建议使用这些列名称。
counts %>%
group_by(`merged$year`) %>%
mutate(C= sum(V1))
# `merged$year` V1 C
# <dbl> <dbl> <dbl>
#1 2001 0.2832134 -1.8231106
#2 2001 -2.1063239 -1.8231106
#3 2002 -1.3826456 -0.2244838
#4 2002 1.1581617 -0.2244838
注意:不需要counts$
,因为我们只传递列名
,对于第二种情况,它是
names(counts)[1:2] <- c("merged1year", "merged1gwmd")
counts %>%
group_by(merged1gwmd, merged1year) %>%
mutate(C= sum(V1))
# merged1year merged1gwmd V1 C
# <dbl> <fctr> <dbl> <dbl>
#1 2001 A 0.9365008 1.344889500
#2 2001 A 0.4083887 1.344889500
#3 2002 B -0.4675696 -0.001339325
#4 2002 B 0.4662303 -0.001339325
counts <- data.frame(`merged$year` = c(2001, 2001, 2002, 2002),
`merged$gwmd` = rep(LETTERS[1:2], each = 2),
V1 = rnorm(4), check.names = FALSE)