Eroding Commitment

September 27, 2015
By

(This article was first published on r – Recommended Texts, and kindly contributed to R-bloggers)

There’s an old saying that goes: “If you dream and want something hard enough, but have no commitment….then you’re probably full of shit”. After having finished the Getting and Cleaning Data course on Coursera, I haven’t typed a single line of R code in a long time; and since i was only just starting out on the basics, my foundations in the language are a little shaky again. So i had to start all over again.

Below is a function that loops through an entire dataframe and find all the column names that contain a given value.

searchCol = function(name, dataframe){
  x = 0 
  newList = c() #This will be vector that would be returned
  
  #Start loop for all the values to be seached for
  
  for(i in 1:length(name)){
    #Start loop for each row in the dataframe...
    for(j in 1:nrow(dataframe)){
      
      #...same thing for the columns
      for(k in 1:ncol(dataframe)){
        
        #If the matching criteria is met, add the value to the newList vector
        if(dataframe[j,k] == name[i]){
          
          newList[x+1] = names(dataframe)[k]
          x = x+1
        }       
      }
    }
  }  
  return(newList)
}

Below is a simple demostration:

mat = data.frame(matrix(1:50, 5, 10))
mat

X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 1 6 11 16 21 26 31 36 41 46
2 2 7 12 17 22 27 32 37 42 47
3 3 8 13 18 23 28 33 38 43 48
4 4 9 14 19 24 29 34 39 44 49
5 5 10 15 20 25 30 35 40 45 50

So to find which columns do the figures 28 and 39 fall in..

tst = c(28, 39)
searchCol(tst, mat)

…we would get:

[1] "X6" "X8"

God, i hate having to start from scratch again.

Tagged: functions, programming, r

To leave a comment for the author, please follow the link and comment on their blog: r – Recommended Texts.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)