Search code examples
rloopsconcatenation

looping the str_c( ) function to concatenate columns in order 1 - 100


I have a data frame (titled fy14bx) in R.

I need to concatenate 100 columns titled 'onset1' , 'onset2', 'onset3' ... 'onset100' with corresponding columns titled 'x08ddx1' ... 'x08ddx100', generating new columns 'c1' - 'c100'

I'm using stingr, specifically:

fy14bx$c1 <- str_c(fy14bx$onset1, "-", fy14bx$x08ddx1)

Obviously I don't want to do this manually (I need to do it in 8 other data frames (fy15... etc) where the column names are slightly different also).

Could anyone help me out please?

Thanks

this was no use

for (i in 1:100) {
  col_name <- paste0("c", i)
  fy14bx[, col_name] <- str_c(fy14bx[, paste0("onset", i)], "-", fy14bx[, paste0("x08ddx", i)])
}

Solution

  • Your code works as expected with a minor tweak:

    library(tidyverse)
    
    fy14bx <- data.frame(onset1 = c(1,2,3,4),
                         onset2 = c(5,6,7,8),
                         onset3 = c(9,10,11,12),
                         x08ddx1 = c(101, 102, 103, 104),
                         x08ddx2 = c(105, 106, 107, 108),
                         x08ddx3 = c(109, 110, 111, 112))
    
    fy14bx$c1 <- str_c(fy14bx$onset1, "-", fy14bx$x08ddx1)
    fy14bx
    #>   onset1 onset2 onset3 x08ddx1 x08ddx2 x08ddx3    c1
    #> 1      1      5      9     101     105     109 1-101
    #> 2      2      6     10     102     106     110 2-102
    #> 3      3      7     11     103     107     111 3-103
    #> 4      4      8     12     104     108     112 4-104
    
    for (i in 1:3) {
      fy14bx[[paste0("c", i)]] <- str_c(fy14bx[, paste0("onset", i)], "-", fy14bx[, paste0("x08ddx", i)])
    }
    
    fy14bx
    #>   onset1 onset2 onset3 x08ddx1 x08ddx2 x08ddx3    c1    c2     c3
    #> 1      1      5      9     101     105     109 1-101 5-105  9-109
    #> 2      2      6     10     102     106     110 2-102 6-106 10-110
    #> 3      3      7     11     103     107     111 3-103 7-107 11-111
    #> 4      4      8     12     104     108     112 4-104 8-108 12-112
    

    Created on 2023-09-26 with reprex v2.0.2