我正在尝试对 R 中数据框的多个列应用相同的函数。
我有一个单独的数据框,其中包含主数据框中的一些列。当主数据框中的列在另一个数据框中时,我想将这两列加在一起,但我似乎无法弄清楚如何访问 mutate_at() 列表中的每个列名。
# random secondary data frame
random <- data.frame(y = rnorm(30, 10), x = rnorm(30, 1), z = rnorm(30, -5))
# master dataframe
fixed <- data.frame(y = rnorm(30, 10), x = rnorm(30, 10), z = rnorm(30, 10), a = rnorm(30, 10))
# trying to add the random secondary values to the master data frame
d <- dplyr::mutate_at(fixed, c('y', 'x', 'z'), function(x){x + random$x})
我可以向每一列添加一个列,但是当我尝试像 x + random[, colnames(random) == x]
这样的操作时,我得到了一个错误。它没有继承列名,我不知道如何访问它们。
有人有什么想法吗?
最佳答案
我们可以使用 base R
方法
fixed[names(random)] <- random + fixed[names(random)]
如果我们需要使用tidyverse
library(tidyverse)
fixed %>%
select(names(random)) %>%
map2_df(., random, ~.x + .y)
关于r - 在 mutate_at() 中访问列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46035844/