我有一个名为A的矩阵, 我想在给定坐标的情况下检索它的元素。我做了坐标转换。 这是我执行此任务的代码,但我不知道,为什么我会收到错误。有人能帮助我吗?它从用户获取坐标(i,j)并在坐标处检索矩阵元素。 错误是:
意外的输入结束
p<- as.numeric(readline(prompt="Pleae enter 1 to get coordinate of number,and 2 to get the number > "));
if(p==1){
# get the number, given coordniate
i<- as.numeric(readline(prompt="Pleae enter i cordinate > "));
j<- as.numeric(readline(prompt="Pleae enter j cordinate > "));
Getvalue<- function(i,j){
if (i>=0) A[2+i,2+j]
else A[2+i,2-j]
Getvalue
}else if (p==2){
# do this
}
答案 0 :(得分:1)
这适合我。
foo <- function(){
p<- as.numeric(readline(prompt="Please enter 1 to get coordinate of number, and 2 to get the number > "))
if(p==1){
# get the number, given coordniate
i<- as.numeric(readline(prompt="Please enter i cordinate > "))
j<- as.numeric(readline(prompt="Please enter j cordinate > "))
Getvalue <- function(i,j){
if (i>=0) {
return(A[2+i,2+j])
} else{
return(A[2+i,2-j])
}
}
Getvalue(i, j)
} else if (p==2){
print("Do this")
}
}
###Example:
> # a dummy matrix
> set.seed(1)
> A <- matrix(sample(100, 100, TRUE), 10)
> # If p=1, i=2, j=2, then 19 should be returned.
> foo() # executing `foo()` to values from the terminal
Please enter 1 to get coordinate of number, and 2 to get the number > 1
Please enter i cordinate > 2
Please enter j cordinate > 2
[1] 19
> foo()
Please enter 1 to get coordinate of number, and 2 to get the number > 2
[1] "Do this"
阅读readline
的文档,并尝试理解其中显示的示例。