Stanciu Adrian
Stanciu Adrian

Reputation: 63

Loop of mutate functions over columns in R

I am trying to create a loop function from several mutate (dplyr package) functions. Each code line below works perfectly, but I am looking for something more elegant (in one line of code, if possible) because I'd need to repeat these five lines 10 more times (for ten additional data frames).

ism.50 is my data.frame with 5 columns and 10,000 rows.

Isim_n20<dbl> Isim_n30<dbl> Isim_n50<dbl> Isim_n100<dbl> Isim_n1000<dbl>
1   1.7789999   3.7416683   1.8228680   1.1573671   1.0336168
2   1.3475063   0.7559132   1.2948982   0.9957275   0.9409909
3   0.5980781   1.7888836   1.4068773   1.0847899   0.9354231
4   1.4656961   1.6271786   1.2401491   1.1348101   0.9749408
5   1.8969097   0.6829495   1.4543307   0.8554704   1.0039841
6   1.3969583   1.1180521   0.7765212   0.8293486   1.0257257
7   0.9155140   1.3892062   0.8045851   1.0480486   1.0344771

breaks is vector breaks = c(0,0.6, 0.7, 0.8, 0.9, 1, 1.2, 1.4, Inf)

labels is a vector labels = c("(0:0.6]", "(0.6:0.7]", "(0.7:0.8]", "(0.8:0.9]", "(0.9:1]", "(1:1.2]", "(1.2:1.4]", ">1.4")

ism.50 <- ism.50 %>% mutate(Intv_n20=cut(ism.50[,1], breaks=breaks, labels=labels))
ism.50 <- ism.50 %>% mutate(Intv_n30=cut(ism.50[,2], breaks=breaks, labels=labels)) 
ism.50 <- ism.50 %>% mutate(Intv_n50=cut(ism.50[,3], breaks=breaks, labels=labels)) 
ism.50 <- ism.50 %>% mutate(Intv_n100=cut(ism.50[,4], breaks=breaks, labels=labels)) 
ism.50 <- ism.50 %>% mutate(Intv_n1000=cut(ism.50[,5], breaks=breaks, labels=labels))

I tried this, but it doesn't work.

for (j in 1:col(ism.50)) {
  ism.50 %>% mutate(Intv_[j]=cut(ism.50[j], breaks=breaks, labels=labels))
}

Upvotes: 0

Views: 144

Answers (1)

NotThatKindODr
NotThatKindODr

Reputation: 719

Try this out, the across function is new but it helps with renaming. Let me know if you need me to tweak it. The nice thing about this is it is scaleable. so if you have 100 columns it would be fine.

 library(tidyverse)
    mutate(ism.50,
          across(starts_with("Isim"), 
          ~cut(., 
               breaks = breaks,
               labels = labels), 
          .names = "replace{col}")) %>% 
          rename_at(vars(starts_with("replace")), ~str_replace(., "replaceIsim", "Intv"))

Upvotes: 2

Related Questions