0

I have a data frame in the following format and (i) want to select all columns that contain the string "EH", (ii) add the value 207 to each observation within the selected columns, (iii) overwrite the columns by its new values.

 NO            date_sub EH17.5a_sub EH17.5b_sub EH12.5a_sub EH12.5b_sub pH17.5_sub pH12.5_sub EH7.5a_sub EH7.5b_sub EH2.5a_sub EH2.5b_sub pH7.5_sub pH2.5_sub Temperature_sub RH_sub Voltage_sub
1  1 2020-06-24 19:00:00      118.67      289.40      198.79      341.28    6.76414    6.80436     358.17     342.98     369.71     171.23   6.79763   6.43233           23.98  39.22      12.353
2  2 2020-06-24 20:00:00       93.04      295.11      162.99      343.38    6.82978    6.87673     361.08     348.22     375.23     171.67   6.97362   6.51686           23.75  39.22      12.357
3  3 2020-06-24 21:00:00       76.67      298.83      142.24      344.17    6.96726    7.03494     362.60     352.05     379.18     172.32   7.20395   6.71439           23.78  39.25      12.353
4  4 2020-06-24 22:00:00       64.27      301.20      128.76      344.32    7.09183    7.17027     363.99     355.68     382.76     174.21   7.37294   6.88682           23.79  39.28      12.346
5  5 2020-06-24 23:00:00       54.24      302.77      117.72      344.28    7.19286    7.27350     364.77     358.63     385.63     176.38   7.49528   7.03470           23.78  39.34      12.346
6  6 2020-06-25 00:00:00       45.46      303.24      107.16      343.47    7.27001    7.34746     365.01     360.91     388.15     177.47   7.58073   7.15890           23.78  39.44      12.363

I have tried the following but is there a more easier way, since I have data frames that contain hundreds of columns where I have to add the value 207.

data_e <- data_e %>%
  mutate(EH17.5a_sub = EH17.5a_sub+207) %>%
  mutate(EH17.5b_sub = EH17.5b_sub+207) # and so on ...
Kris
  • 15
  • 3

2 Answers2

0

You can use across in dplyr to apply a function to multiple columns.

library(dplyr)
data_e <- data_e %>% mutate(across(contains("EH"), ~. + 207))
#Use `mutate_at` for `dplyr` < 1.0.0
#data_e <- data_e %>% mutate_at(vars(contains("EH")), ~. + 207)

Or in base R :

cols <- grep('EH', names(data_e))
data_e[cols] <- data_e[cols] + 207
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

You can use tidyverse functions. starts_with will find the pattern you need.

library(tidyverse)
data %>%
   mutate(new_variable = select(data, starts_with("EH")) + 207)
rg4s
  • 811
  • 5
  • 22