用R中的mutate_at覆盖很多列? [英] Overwrite lot of columns with mutate_at in R?

查看:617
本文介绍了用R中的mutate_at覆盖很多列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下dataframe,我试图使用具有lambda功能但没有运气的dplyr::mutate_at突变除cd以外的所有列:

Given the following dataframe I am trying to mutate all but c and d columns using dplyr::mutate_at with lambda function but without luck:

structure(list(a = c(1, 2, 3), b = c(43, 2, -1), c = c(234242, 
-223, 1), d = c(1, 1, 2)), .Names = c("a", "b", "c", "d"), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))

df %>% mutate_at(vars(-c("c", "d"), funs(x = x + rnorm(1, mean = mean(x), sd = sd(x))

我想覆盖现有的a和b列,而无需手动进行相互变异. 请告知.

I want to overwrite the existing a and b columns without the need to mutate each other manually. Please advise.

注意:我的真实数据集相似,但有50列要进行变异并添加此正态分布随机变量值.除了特定的列,我想自动化它.

NOTE: My real dataset is similar but it has 50 columns to mutate and add this normal distribution random variable value. I want to automate it except for specific columns.

推荐答案

您快到了.有两点需要更改:

You were nearly there. Two little things to change:

  1. x更改为.
  2. 访问不带引号的列名:-c(c, d)而不是-c("c", "d").
  1. Change x to .
  2. Access the column names without quote marks: -c(c, d) instead of -c("c", "d").

这导致

df %>% mutate_at(vars(-c(c, d)), funs(. + rnorm(1, mean = mean(.), sd = sd(.))))                                    

效果很好.输出为:

# A tibble: 3 x 4
      a     b       c     d
  <dbl> <dbl>   <dbl> <dbl>
1  3.05  56.6  234242     1
2  4.05  15.6    -223     1
3  5.05  12.6       1     2

这篇关于用R中的mutate_at覆盖很多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆