Search code examples
rdataframeconcatenationmapplystringi

How to loop through mapply in R?


I am trying to concatenate strings using mapply function in R. However, I want one of the strings to be variable in mapply function. I have a snippet of my code below:

strings<-data.frame(x=c("dsf","sdf","sdf"))
strings2<-data.frame(extension=c(".csv",".json",".xml"))

for (i in 1:3)
{
  strings_concat<-mapply(function(string1,string2) paste0(string1,string2),strings$x,strings2$extension[i])%>%
    data.frame()%>%
    unlist()%>%
    data.frame()

 #dosomething with strings_concat
}

But this is giving me the last iteration only

strings_concat

dsf.xml
sdf.xml
sdf.xml

bust instead, the desired output is as follows:

strings_concat

dsf.csv 
sdf.csv 
sdf.csv 

dsf.json 
sdf.json 
sdf.json 

dsf.xml
sdf.xml
sdf.xml

At every iteration, i want to combine strings_concat with another dataframe and save it. Can anyone help me if there is an easy way to do this in R?


Solution

  • Perhaps, outer is a better option here :

    strings_concat <- c(outer(strings$x, strings2$extension, paste0))
    strings_concat
    #[1] "dsf.csv"  "sdf.csv"  "sdf.csv"  "dsf.json" "sdf.json" "sdf.json" 
    #    "dsf.xml"  "sdf.xml"  "sdf.xml" 
    

    You can add it in a data.frame :

    df <- data.frame(strings_concat)
    

    If you want to add some additional steps at each iteration you can use lapply :

    lapply(strings2$extension, function(x) {
      strings_concat <- paste0(strings$x, x)
      #do something with strings_concat
    })