R: How to avoid 2 'for' loops in R in this function

R: How to avoid 2 'for' loops in R in this function

By : user2954023
Date : November 21 2020, 07:31 AM
With these it helps I know there are many topics on how to avoid R loops, but I was not able to understand how I could vectorize my iterations. I have a data set which here I represent by m. I want to generate a new matrix with this function, that will be composed by the p.values of the correlation coefficients of each column of the data (m). , You could use rcorr from library(Hmisc)
code :
  outer(1:ncol(m),1:ncol(m), FUN= Vectorize(function(x,y) 
                              cor.test(m[,x], m[,y])$p.value))
 akrun <- function() {outer(1:ncol(m1),1:ncol(m1), 
            FUN= Vectorize(function(x,y) cor.test(m1[,x],

 akrun2 <- function(){rcorr(m1)$P}
 agstudy <- function() {M <- expand.grid(seq_len(ncol(m1)),
      mapply(function(x,y)cor.test(m1[,x], m1[,y])$p.value,M$Var1,M$Var2)}
 vpipk <-function(){
        n <- ncol(m1)
   for (i in 1:(n-1)){
      for (t in (i+1):n){

 nrussell <- function(){
   sapply(1:ncol(m1), function(z){
   sapply(1:ncol(m1), function(x,Y=z){
 m1 <- matrix(rnorm(1e2*1e2),nrow=1e2,ncol=1e2)
 microbenchmark(akrun(), akrun2(), agstudy(), vpipk(),
                    nrussell(), unit='relative', times=10L)
 #Unit: relative
 #  expr      min       lq     mean   median       uq      max neval cld
 #   akrun() 257.2310 255.9766 252.2163 254.4946 248.9807 246.5429    10   c
 #  akrun2()   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000    10   a  
 # agstudy() 255.5920 258.0813 253.5411 256.0581 250.4833 249.0503    10   c
 #   vpipk() 125.8218 126.3337 125.4592 126.8479 124.9835 124.1383    10   b 
 #nrussell() 257.9283 256.8480 252.5297 256.0160 250.8853 242.0896    10   c
 # user  system elapsed 
#403.563   0.751 404.198 

 #  user  system elapsed 
 # 3.110   0.008   3.117 

 #  user  system elapsed 
 #445.108   0.877 445.947 

#  user  system elapsed 
#155.597   0.224 155.760 

#  user  system elapsed 
#452.524   1.220 453.713 

Share : facebook icon twitter icon
How to avoid function call in js in large loops?

How to avoid function call in js in large loops?

By : Yousef Mohamed Youse
Date : March 29 2020, 07:55 AM
I hope this helps . I'm not sure if there's your case, but sometimes it is handy to use tool called cpp2js. It allows you to create inline C++ functions inside your JavaScript code. Those C++ code is executed on server. Here you can find documentation: http://www.speqmath.com/tutorials/cpp2js/index.html.
How to avoid for-loops with multiple criteria in function which()

How to avoid for-loops with multiple criteria in function which()

By : swati730
Date : March 29 2020, 07:55 AM
this will help You can use dcast from package reshape2, with a custom function to sum your values:
code :
dcast(mydata, name~tag, value.var='value', fun.aggregate=sum)
xtabs(value~name+tag, mydata)
funcPer = function(){
    S <- matrix(data=NA, nrow=length(unique(mydata$tag)), ncol=length(unique(mydata$name)))
    for(i in 1:nrow(S)){
      for (j in 1:ncol(S)){
        foo <- which(mydata$tag == unique(mydata$tag)[i] & mydata$name == unique(mydata$name)[j])
        S[i,j] <- sum(mydata$value[foo])

colonel1 = function() dcast(mydata, name~tag, value.var='value', fun.aggregate=sum)

colonel2 = function() xtabs(value~name+tag, mydata)

#> system.time(colonel1())
#  user  system elapsed 
#   0.01    0.00    0.01 
#> system.time(colonel2())
#   user  system elapsed 
#   0.05    0.00    0.05 
#> system.time(funcPer())
#   user  system elapsed 
#   4.67    0.00    4.82 
How to cleanly avoid loops in recursive function (breadth-first traversal)

How to cleanly avoid loops in recursive function (breadth-first traversal)

By : Lenny
Date : March 29 2020, 07:55 AM
With these it helps Check out:
How do I pass a variable by reference?
Using reduce, map or other function to avoid for loops in python

Using reduce, map or other function to avoid for loops in python

By : Sheraz Ahmed
Date : March 29 2020, 07:55 AM
it helps some times I have a program working for calculating the distance and then apply the k-means algorithm. I tested on a small list and it's working fine and fast, however, my original list is very big (>5000), so it's taking forever and I ended it up terminating the running. Can I use outer() or any other parallel function and apply it to the distance function to make this faster?? On the small set that I have:
code :
import numpy as np 

strings = ['cosine cos', 'cosine', 'cosine???????', 'l1', 'l2', 'manhattan']


data = np.zeros((k,k))

for i,string1 in enumerate(strings):
    for j,string2 in enumerate(strings):
        data[i][j] = 1-Levenshtein.ratio(string1, string2)

print data
Avoid function declaration in for loops for promises

Avoid function declaration in for loops for promises

By : Vishnu R
Date : March 29 2020, 07:55 AM
it fixes the issue Move the isFinished flag and the function out of refreshProfiles and into the parent closure (so that both functions have access to it). Be sure to reset isFinished to false whenever the function is first called externally.
Related Posts Related Posts :
  • Selecting unique rows using sqldf package in R
  • why am i getting "month.observed" object not found even though it has been defined in R?
  • Using German characters (ü, ö, ä, etc.) in text analysis (R)
  • R JAGS: Dimension mismatch
  • R - How to create a function that accepts a code block as parameter?
  • How do I manually set geom_bar fill color in ggplot
  • How can I get my points to connect in a plot and show a trend with NA values in data?
  • Read SPecific lines of a CSV file in R-language
  • ggplot stacked bar plot from 2 separate data frames
  • auto.arima not parallelizing
  • Histogram of binned data frame in R
  • R rewriting stringmanipulations implemented in loop to the R-way
  • get first entries in rows of list?
  • Conditionally removing rows from a matrix in R
  • Using a loop to find P(-1.5<Y<1.5) for a range of sample sizes
  • R-Count and list the maximum count row by row
  • Include Iverson Bracket in R documentation
  • update a data frame and environment in R
  • How to write dynamic cumulative multiple in R
  • format time using as.POSIX in R
  • Change the class of multiple columns
  • Remove period and spaces within column headings nested in a list of data frames
  • R: error message --- package error: "functionName" not resolved from current namespace
  • labels with geom_text ggplot2
  • Passing mongodb ISODate in R
  • Importing "csv" file with multiple-character separator to R?
  • Change row names of a table obtained from a lm regression using xtable function
  • R language iterate over R object
  • How do you delete the header in a dataframe?
  • Re coding in R using complicated statement
  • accumulating functions and closures in R
  • How do you combine two columns into a new column in a dataframe made of two or more different csv files?
  • Twitter authentication fails
  • Summing Values of One Vector Conditional on Values of Another Vector
  • draw cube into 3D scatterplot in RGL
  • lme4 translate formula to code in 3-level model
  • How to draw single axis plot in R
  • Combine geom_tile() and facet_grid/facet_wrap and remove space between tiles (ggplot2)
  • Use snpStats with R version 3.0.1
  • Makefile gives strange error while compiling markdown file into .docx file
  • How to determine whether a points lies in an ellipse
  • Summarize data already grouped in r
  • Is the bigvis package for R not available for R version 3.0.1?
  • Operator overloading in R reference classes
  • How to enable user to switch between ggplot2 and gVis graphs in R Shiny?
  • Is there an easy way to separate categorical vs continuous variables into two dataset in R
  • Correct previous year by id within R
  • Installation of rdyncall package for R
  • ggplot2 plot that evaluates the percentage and mean of a third variable at intersecting points
  • Error Handling with Lapply
  • data.table - split multiple columns
  • How to compute the overall mean for several files in R?
  • R: Graph Plotting: Subscripts in the legend like LaTeX
  • Restructuring data in R
  • Distance of pointsfrom cluster centers after K means clustering
  • R incorrect value of date function
  • Package "Imports" not loading in R development package
  • r - run a user defined function several times by taking column elements as parameters
  • Create input$selection to subset data AND radiobuttons to choose plot type in Shiny
  • Generate crosstabulations from dataframe of categorical variables in survey
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org