r - 在 mutate_at() 中访问列名

标签 r dplyr

我正在尝试对 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/

相关文章:

r - 如何迭代函数中的条目以创建两个新的字符向量

r - dplyr 选择助手的交集

返回另一个时间范围内的数据子集时间范围?

重新排列不平衡的时间序列数据

r - 将向量传递到 all() 以测试相等性

在 R 中重新编码除一个变量之外的所有变量

r - Slice_min 和 Slice_max 关系说明

r - 统计每行第一个0的位置

r - Google Speech API 请求超出限制 R

r - 在数据帧 R 中取消嵌套数据帧