#r
#r
Вопрос:
Я пытаюсь создать график, который использует сюжетные функции и соединяет линии. Это будет сколько угодно строк. Я хочу запрашивать аргументы до тех пор, пока на входе не будет «нет». Пример:
R:"Enter slope, intercept"
User:*input*
R:"Enter slope, intercept"
User:*input*
R:"Enter slope, intercept"
User:"no"
R:"Thank you for inputs"
затем появляется график
Комментарии:
1. Я думаю, вы хотите
readline
внутриwhile
цикла?
Ответ №1:
myfunc <- function() {
slopes <- intercepts <- numeric(0)
while (TRUE) {
user <- tolower(readline("Enter 'slope,intercept': "))
if (trimws(user) == "no") {
break
}
if (!nzchar(user)) {
warning("Don't get short with me, I asked you a question ... or type 'no' to exit", call. = FALSE)
next
}
parsed <- tryCatch(
unlist(lapply(strsplit(user, ",")[[1]], as.numeric)),
warning = function(w) w, error = function(e) e)
if (inherits(parsed, c("error","warning"))) {
warning("That made no sense to me ('", conditionMessage(parsed),
"'), please try again", call. = FALSE)
next
}
if (length(parsed) != 2L) {
warning("I did not see (exactly) two values there, please try again", call. = FALSE)
next
}
if (anyNA(parsed) || !is.numeric(parsed)) {
warning("I see two things but at least one is non-numeric, please try again", call. = FALSE)
next
}
slopes <- c(slopes, parsed[[1]])
intercepts <- c(intercepts, parsed[[2]])
lims <- range(c(0, intercepts))
plot(NA, type = "n", xlim = lims, ylim = lims)
ign <- mapply(abline, intercepts, slopes)
}
message("Thank you for your inputs, have a nice day")
}
Выполнение:
myfunc()
# Enter 'slope,intercept':
2,3
# Enter 'slope,intercept':
3,2
# Enter 'slope,intercept':
2.3
# Warning: I did not see (exactly) two values there, please try again
# Enter 'slope,intercept':
2,abc
# Warning: That made no sense to me ('NAs introduced by coercion'), please try again
# Enter 'slope,intercept':
2,3,4
# Warning: I did not see (exactly) two values there, please try again
# Enter 'slope,intercept':
no
# Thank you for your inputs, have a nice day
Вам нужно подумать, как вы хотите установить ограничения x / y, в настоящее время это наивно и, вероятно, недостаточно.
Комментарии:
1. Спасибо, шеф. Это было полезно. Можете ли вы объяснить наклоны <- перехваты <- числовые (0) для меня?
2. Цепное присвоение. То же самое,
slopes <- numeric(0) ; intercepts <- numeric(0)
что и .