2

I have a giant data frame. The first column is names. I would like to type in the console the name and then it outputs a predetermined row corresponding to that name.

For example:

Data Frame =    
Name Height Weight Shoes Hats
1 Joe  60     150    13    4
2 Nick 55     100    10    10
3 Dan  80     250    40    50

I would like to Search for Nick, the function searches in the first column for Nick. Once it finds Nick it prints out the Shoes value. So it needs to search in the first column and then return what ever the corresponding shoe value is.

Benjamin
  • 11,560
  • 13
  • 70
  • 119
Student99
  • 37
  • 2

2 Answers2

3

We can create the function by arguments for the data, column names, and value to compare, then extract the column with [[, do the comparison == and extract the corresponding second column value

f1 <- function(dat, col1, col2, value) {
            dat[[col2]][dat[[col1]] == value]
     }

f1(df1, "Name", "Shoes", "Nick")
#[1] 10

data

df1 <- structure(list(Name = c("Joe", "Nick", "Dan"), Height = c(60L, 
55L, 80L), Weight = c(150L, 100L, 250L), Shoes = c(13L, 10L, 
40L), Hats = c(4L, 10L, 50L)), class = "data.frame", row.names = c("1", 
"2", "3"))
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can easily use which to find the row numbers associated with "Nick" and then use that to select the rows from the dataframe.

which(df[,"Name"]=="Nick") #provides row number so....

df[which(df["Shoes", "Name"]=="Nick"),] #... will return all rows with the matching name and "Shoes" will make it return just that columns data.

If you want it in a function

NameSearch<-function(data, Name, column2search, column2return){
  data[which(data[,column2search]==Name),column2return] 
}

NameSearch(df, "Nick", "Name", "Shoes")

I recreated your example dataframe here

df<-data.frame(matrix(c("Joe", 60, 150, 13, 4, "Nick", 55, 100, 10, 10, "Dan", 80, 250, 40, 50), nrow=3, byrow=T))
colnames(df) <- c("Name", "Height", "Weight", "Shoes", "Hats")
Tanner33
  • 120
  • 2
  • 15