简体   繁体   English

仅使用dplyr突变数值列的值,并且仅对数据帧的第一行和最后一行进行突变

[英]Mutate value only for numeric columns AND only in the first and last row of a data frame using dplyr

Given a data frame like: 给定一个数据框,例如:

library(dplyr)
library(lubridate)

df <- data.frame(
  date = seq(ymd('2018-01-01'), ymd('2018-01-10'), by = 'days'),
  location = "AMS",
  V1 = seq(1:10),
  V2 = seq(11:20)  
)

I would like to use dplyr to change the value of the first and last row, and only in numeric columns. 我想使用dplyr更改第一行和最后一行的值,并且仅在数字列中。

I can do it for one column, as in: 我可以在一列中执行此操作,如下所示:

df %>%
  mutate(V1 = ifelse(row_number()==1, mean(V1)*100, V1)) %>%
  mutate(V1 = ifelse(row_number()==nrow(.), mean(V1)*100, V1)) 

However I cannot manage to find a way to use mutate_at or mutate_if to do that for all numeric columns at once. 但是,我无法找到一种方法来使用mutate_atmutate_if一次对所有数字列执行此操作。 Could you help me with that? 你能帮我吗?

I think this addresses your issue: 我认为这可以解决您的问题:

df <- data.frame(
  date = seq(ymd('2018-01-01'), ymd('2018-01-10'), by = 'days'),
  location = "AMS",
  V1 = 1:10,
  V2 = 11:20  
)

df %>% mutate_at(vars(V1, V2),
                 funs(ifelse(row_number() %in% c(1, n()), mean(.)*100, .)))

         date location  V1   V2
1  2018-01-01      AMS 550 1550
2  2018-01-02      AMS   2   12
3  2018-01-03      AMS   3   13
4  2018-01-04      AMS   4   14
5  2018-01-05      AMS   5   15
6  2018-01-06      AMS   6   16
7  2018-01-07      AMS   7   17
8  2018-01-08      AMS   8   18
9  2018-01-09      AMS   9   19
10 2018-01-10      AMS 550 1550

If you'd like to do it on all numeric columns, you can just use mutate_if with is.numeric as the .predicate argument. 如果要在所有数字列上执行此操作,则可以仅将mutate_ifis.numeric用作.predicate参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用`colnames`的数值来重新计算data.frame中的列,使用`dplyr`的`mutate_at`或替代方法 - Use numeric value of `colnames` to recalculate columns in a data.frame using `dplyr`'s `mutate_at` or an alternative 仅使用dplyr选择器跨几列对值进行突变 - Mutate a value across several columns using dplyr selectors only 为什么函数的dplyr :: mutate只影响第一行而不影响其余部分 - Why dplyr::mutate of a function only affect the first row not the rest 使用dplyr中的select按行值对数据帧中的子集列 - subset columns in a data frame by a row value using select in dplyr Dplyr:仅当行值 > 0 时才使用跨汇总取列的平均值 - Dplyr: using summarise across to take mean of columns only if row value > 0 重新排列R中的数据框列(mutate,dplyr) - Rearranging data frame columns in R (mutate, dplyr) dplyr使用来自单独数据帧子集的值进行突变 - dplyr mutate using value from a subset of separate data frame 从数据框中仅选择数字列 - Selecting only numeric columns from a data frame 使用mutate创建新列,该变量与数据帧(dplyr)中每一行的一组指定列的内容有关 - Creating a new column using mutate which is some function of the contents of a specified set of columns for each row in a data frame (dplyr) 使用dplyr可以仅将数据类型为整数的列更改为数字数据类型 - using dplyr can we change to numeric data type only those columns for which data type is integer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM