Eroding Commitment

[This article was first published on r – Recommended Texts, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)