Eroding Commitment

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.

Advertisements
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s