工作流中的大多数

工作流中的大多数

本文介绍了向管道 R 工作流中的大多数 data.frame 变量名称添加前缀或后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 data.frame 中的大多数变量名称添加后缀或前缀,通常是在它们以某种方式全部转换之后和执行连接之前.我没有办法在不破坏管道的情况下做到这一点.

I want to add a suffix or prefix to most variable names in a data.frame, typically after they've all been transformed in some way and before performing a join. I don't have a way to do this without breaking up my piping.

例如,使用此数据:

library(dplyr)
set.seed(1)
dat14 <- data.frame(ID = 1:10, speed = runif(10), power = rpois(10, 1),
                    force = rexp(10), class = rep(c("a", "b"),5))

我想得到这个结果(注意变量名):

I want to get to this result (note variable names):

  class speed_mean_2014 power_mean_2014 force_mean_2014
1     a       0.5572500             0.8       0.5519802
2     b       0.2850798             0.6       1.0888116

我目前的做法是:

means14 <- dat14 %>%
  group_by(class) %>%
  select(-ID) %>%
  summarise_each(funs(mean(.)))

names(means14)[2:length(names(means14))] <- paste0(names(means14)[2:length(names(means14))], "_mean_2014")

有没有其他方法可以替代那条打断我的管道的笨重的最后一行?我看过 select()rename() 但不想明确指定每个变量名,因为我通常想重命名所有 except 单个变量,并且可能具有比本例中更宽的 data.frame.

Is there an alternative to that clunky last line that breaks up my pipes? I've looked at select() and rename() but don't want to explicitly specify each variable name, as I usually want to rename all except a single variable and might have a much wider data.frame than in this example.

我正在想象一个近似于这个虚构函数的最终管道命令:

I'm imagining a final piped command that approximates this made-up function:

appendname(cols = 2:n, str = "_mean_2014", placement = "suffix")

据我所知,这是不存在的.

Which doesn't exist as far as I know.

推荐答案

你可以将函数传递给 rename_at,所以这样做

You can pass functions to rename_at, so do

 means14 <- dat14 %>%
  group_by(class) %>%
  select(-ID) %>%
  summarise_all(funs(mean(.))) %>%
  rename_at(vars(-class),function(x) paste0(x,"_2014"))

这篇关于向管道 R 工作流中的大多数 data.frame 变量名称添加前缀或后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:55