将用户输入存储到R中的数据框中

时间:2018-05-21 12:34:08

标签: r dataframe input

我想在R中获取用户输入并将它们存储到匹配的数据帧列中。例如:

Month Year  Value       No
4     2016  114235.00   A22
5     2016  114235.00   A22
6     2016  114235.00   A22

my.name <- readline(prompt="Year: "))
my.month <- as.integer(readline(prompt="Month: "))
my.off <- as.integer(readline(prompt="Value: "))

我该怎么做?

1 个答案:

答案 0 :(得分:1)

readData <- function() {
  df <- data.frame(Month = c(), Year = c(), Value = c())
  while(TRUE) {
    my.year <- readline(prompt="Year: ")
    # stop reading if no year was typed in
    if (my.year == '')
      break
    my.month <- as.integer(readline(prompt="Month: "))
    my.val <- as.integer(readline(prompt="Value: "))
    # add the read data to the bottom of the dataframe
    df <- rbind(df, data.frame(Month = c(my.month), Year = c(my.year), Value = c(my.val)))
  }
  df
}
# now call the function, it will allow inputs until an empty year is typed
readData()