Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speeding up an R for loop to paste multiple variables together

Tags:

r

I'm new here but could use some help. I have a list of data frames, and for each element within my list (i.e., data.frame) I want to quickly paste one column in a data set to multiple other columns in the same data set, separated only by a period (".").

So if I have one set of data in a list of data frames:

list1[[1]]

A  B  C
2  1  5
4  2  2

Then I want the following result:

list1[[1]]

 A    B   C
2.5  1.5  5
4.2  2.2  2  

Where C is pasted to A and B individually. I then want this operation to take place for each data frame in my list.

I have tried the following:

pasteX<-function(df) {for (i in 1:dim(df)[2]-1) {
df[,i]<-as.numeric(sprintf("%s.%s", df[,i], df$C))
}
return(df)}
list2<-lapply(list1, pasteX)

But this approach is verrrry slow for larger matrices and lists. Any recommendations for making this code faster? Thanks!

like image 836
zeekster26 Avatar asked Dec 04 '25 23:12

zeekster26


1 Answers

Assuming everything is integers < 10

lapply(list1, function(x){
    x[,-3] <- x[,-3] + x[,3]/10
    x})
like image 84
IceCreamToucan Avatar answered Dec 06 '25 15:12

IceCreamToucan