Jazzmine
Jazzmine

Reputation: 1875

Read data into dataframe by row with R

I'm learning to write an R function to get input from the keyboard to create a set of new rows into a new dataframe and return the new dataframe:

enterData <- function(numRows, df_name="enterDataDF"){
  #two parameters: how many times to run (how many rows do you want) and 
                    dataframe name to be preserved

  #create an empty dataframe with slots for number of rows user specifies
  tempdf <- data.frame(id=1:numRows)

  #get input data from keyboard
  for (i in 1:numRows)
  {
    userID      <- as.character(readline("What is userID? "))
    eventTime   <- as.numeric(readline("What is Time To Event? "))
    outcome     <- as.character(readline("What is Outcome (0=fail, 1=success)? "))

    #put row just entered into the ultimate dataframe
    df_name <- rbind(tempdf, c(userID, eventTime, outcome))

    #print a blank line for readability
    print("")
  }

  #show the inputted data
  print("Displaying collected data")
  df_name

  #return dataframe back to calling program
  return (df_name)
}

I'm getting a couple of errors as shown below:

Error #1 Code: for (i in 1:numRows) Error: Error in 1:numRows : NA/NaN argument

Error #2 Code: df_name Error: object 'df_name' not found

Error #3 Code: return (df_name) Error: object 'df_name' not found

Can you tell me what is causing the errors?

Also, how would I call the function, just call the function, or do I need to receive the dataframe via a variable like x<- enterData?

Any improvements on the approach to getting the rows of data would be appreciated.

Thanks

Upvotes: 0

Views: 132

Answers (1)

JKJ
JKJ

Reputation: 212

Are you running this on Rstudio or R? One error might be to check your comments to make sure they are actually being commented out. I ran it on Rstudio and on the console. Everything is printing out except the eventTime and outcome. Here is how I ran it

Upvotes: 1

Related Questions