r - 使用 `colnames` 的数值使用 `dplyr` 的 `mutate_at` 或替代方

我有一个 df,我想根据那些列 colnames 的值重新计算一些列:

library(dplyr)
df <- data.frame(year = 1:3, "10" = 0:2, "20" = 3:5)
colnames(df)[2:3] <- c("10", "20")
df
  year 10 20
1    1  0  3
2    2  1  4
3    3  2  5

预期的输出是 col_name - col_values。我可以生成预期的输出:

df %>% mutate(`10` = 10 - `10`) %>% mutate(`20` = 20 - `20`)
  year 10 20
1    1 10 17
2    2  9 16
3    3  8 15

如何在不显式复制相关 colnames 值的情况下生成相同的输出?

我尝试了以下代码(有效):

df %>% mutate(`10` = as.numeric(colnames(.)[2]) - `10`) %>% mutate(`20` = as.numeric(colnames(.)[3]) - `20`)

所以我试图进一步减少这个但只能想到:

df %>% mutate_at(vars(-year), ~ as.numeric(colnames(.)[.]))

这显然不能工作,因为 . 有两个含义..

如何使用 mutate_at 或替代方法实现我的预期输出?

最佳答案

reshape ,做事,然后再次 reshape :

gather(df, key = "k", value = "v", -year) %>% 
  mutate(v = as.numeric(k) - v) %>% 
  spread(key = "k", value = "v")

#   year 10 20
# 1    1 10 17
# 2    2  9 16
# 3    3  8 15

关于r - 使用 `colnames` 的数值使用 `dplyr` 的 `mutate_at` 或替代方法重新计算 data.frame 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55903974/

相关文章:

macos - Docker Mac 替代 --net=host

extjs - 商店的监听器功能在网格更新时触发两次

macos - undefined symbol : "boost::system::generic

asp.net-mvc - 带有 Ckeditor 的 MVC2 应用程序“具有潜在危险的 Requ

scala - 如何使用 Scala 在 lagom 中为 NoHostAvailableExcep

extjs - 在绑定(bind) View 中应用条件

visual-studio-2015 - IApplicationBuilder 不包含 UseWe

selenium-webdriver - 在 Heroku 上使用 webdrivers selen

forms - 如何使用 cakephp 和 twitter bootstrap 在 poSTLin

azure - 使用 Azure SQL 的 ASP.Net Core 2.1 Serilog SQ