-1

I have a dataframe with column names: X, time, "indoors_c" and "outdoors_c". Where time is >= 13, I want to replace the value of the rows in columns with names containing the string "_c" with 0. How do I do this without referring to the entire column name? I am using R studio

nc97
  • 1
  • 1
  • 1
    Please can you share a reproducible example of your data using ``dput()`` and edit the output into your question. Thanks. – user438383 May 23 '21 at 18:05
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick May 23 '21 at 18:06

2 Answers2

2

Using functions from tidyverse, sse across() together with contains() to select the columns over which to apply the function. Then use if_else for the function, putting 0 values if column time is above/below some value.

Small reproducible example:

library(tidyverse)


data <- tibble(X=rnorm(20), time=1:20, indoors_c=rnorm(20),  outdoors_c=rnorm(20))

data %>% 
  mutate(across(contains("_c"), ~ if_else(time>=13, 0, .)))
#> # A tibble: 20 x 4
#>          X  time indoors_c outdoors_c
#>      <dbl> <int>     <dbl>      <dbl>
#>  1 -1.67       1   -2.41      -1.44  
#>  2  1.00       2    0.113      0.701 
#>  3  0.386      3    0.0248    -0.425 
#>  4  0.266      4   -0.431     -0.0722
#>  5 -0.206      5    0.255     -1.34  
#>  6 -0.617      6    0.441      0.761 
#>  7  1.42       7    0.481     -0.892 
#>  8  0.207      8   -0.112     -0.906 
#>  9  1.42       9   -0.465     -0.527 
#> 10 -0.934     10   -2.21       2.95  
#> 11 -0.419     11   -0.639     -0.113 
#> 12  0.812     12   -0.180      0.440 
#> 13  0.331     13    0          0 
#> 14 -0.454     14    0          0     
#> 15 -0.0290    15    0          0     
#> 16  0.167     16    0          0     
#> 17 -0.150     17    0          0     
#> 18  0.922     18    0          0     
#> 19  1.77      19    0          0     
#> 20  1.62      20    0          0

Created on 2021-05-23 by the reprex package (v2.0.0)

DeBARtha
  • 460
  • 6
  • 17
Matifou
  • 7,968
  • 3
  • 47
  • 52
1

We can use case_when

library(dplyr)
data %>%
    mutate(across(ends_with('_C'), ~ case_when(time > 0 ~ 0, TRUE ~ .)))
akrun
  • 874,273
  • 37
  • 540
  • 662