0

Write a function in R that receives two parameters. The first is data.fame or data.table, the second is a vector of integers. The function of the function is to return the rows of the first parameter whose serial number was in the vector in a new data.table or data.frame variable. If there is a larger number in the vector than the number of rows in the data table, then write a message for that number that the line was not included in the output.

I tried, but it's not a vector, and I don't know, how can I do this

get_vecrow = function(data, vecrow){
  if (vecrow <= nrow(data) & vecrow > 0){
    print(data[vecrow,])
  }
  else{
    print("Row: ")
    print(nrow(data))
  }
}
Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
  • `print` doesn't return a vector, it outputs to the console and returns NULL. Could you confirm what you mean by "serial number" in this context, is there a specific column of the dataframe that you are supposed to be looking in? – Russ Hyde Mar 25 '19 at 18:55
  • Possible duplicate of [how to extract a subset of a data frame based on a condition involving a field?](https://stackoverflow.com/questions/3445590/how-to-extract-a-subset-of-a-data-frame-based-on-a-condition-involving-a-field) – divibisan Mar 25 '19 at 19:20

1 Answers1

0
# Dummy data
vector = c(1,2,10,400) # Vector of numbers want to find in df
df = data.frame(data = seq(1,100,1), random = "yee") # dummy df 

# Loop to match vector numbers with data frame - on match save data frame row
grab_row = list() # Initialize output list
for (i in 1:nrow(df)){
  if(df$data[i] %in% vector) {  # Check that any number in the vector is in the data frame column
    grab_row[[i]] = df[i,] # if TRUE, grab the data frame row
  } 
} # end

# Output df with rows that matched vector 
out = do.call(rbind,grab_row)

For the output

   data random
1     1    yee
2     2    yee
10   10    yee
Andrew Bannerman
  • 1,235
  • 2
  • 16
  • 36