0

Suppose I build mystring in a for loop as followings in r:

mystring = "" colorIndex = 17 for(i in 1:ncol(myTable)){ mystring = paste(mystring, paste("$('td:eq(",i, ")', nRow).attr('title', full_text);", sep = "")) mystring = paste(mystring, paste("$('td:eq(",i,")', nRow).css('cursor', 'pointer');", sep = "")) mystring = paste(mystring, "if(aData[",colorIndex,"] == 0){ $(nRow).css('background-color','#f8f8ff') }else if(aData[",colorIndex,"]==1){ $(nRow).css('background-color','#9EFAC5') }else{ $(nRow).css('background-color','#FAF99E') };", sep ="") } 

Now, suppose my table had 60 columns. I'm trying to figure out the easiest way to do this. Do I need to make one large string, with a special character and then grep out the character? How to iterate over the i efficiently is throwing me. However, given how slow R is with strings, I would prefer not to do this in a loop.

5
  • You could use an apply function, which might perform better, and might leave the code looking a bit cleaner. Commented Jan 24, 2018 at 6:08
  • @TimBiegeleisen: But how would that concatenate at the end? Commented Jan 24, 2018 at 6:09
  • just pondering aloud, would this be easier in javascript itself? Commented Jan 24, 2018 at 6:20
  • Perhaps -- but my javascript is somewhat limited. what would be the bet way to do it directly in javascript? Commented Jan 24, 2018 at 6:23
  • post it as a javascript question? there is a huge community on js here Commented Jan 24, 2018 at 6:30

2 Answers 2

1

You don't need a loop at all because paste is vectorized:

i <- 1:ncol(myTable) yourstring <- paste( paste0( paste0(" ", "$('td:eq(",i, ")', nRow).attr('title', full_text);"), " ", paste0("$('td:eq(",i,")', nRow).css('cursor', 'pointer');"), "if(aData[",colorIndex,"] == 0){ $(nRow).css('background-color','#f8f8ff') }else if(aData[",colorIndex,"]==1){ $(nRow).css('background-color','#9EFAC5') }else{ $(nRow).css('background-color','#FAF99E') };" ), collapse = "") 
Sign up to request clarification or add additional context in comments.

Comments

1

Maybe you could use glue for this, because it makes things look cleaner, and put combinations in a data frame in advance, such that you don't need the loop:

myTable <- iris mystring <- "your string with some glue-elements in it: i = {paste_df$i} and colorIndex = {paste_df$colorIndex}" paste_df <- data.frame(i = seq_len(ncol(myTable)), colorIndex = 17) string <- glue::glue(mystring) # or, a little messy but the same, with paste0: string <- paste0("your string with some glue-elements in it: i = ", paste_df$i, " and colorIndex = ", paste_df$colorIndex) # and in the end, collapse the string: paste0(string, collapse = "") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.