R readLines from console- how to signal end of input - r

I want to use readLines function for input from console of variable number of lines and store it to a vector:
v <- readLines()
How do I signal the end of input? Control-c cancels the process and no 'v' object is formed. Control-Z stops R program altogether. Typing 'EOL' or 'EOF' do not work.
I tried following function but it gives error:
getinput = function(){
v=""
while(TRUE){
line = readLines(n=1)
if(line=="") break
v = v+line
}
v
}
> getinput()
firstentry
Error in v + line : non-numeric argument to binary operator
>
I am using R on Debian Linux. Thanks for your help.

<CTRL-D> will signal EOF. If you're using ess, try C-c C-c. Hope that helps and good luck. Leave a comment if you need further assistance.

Related

passing variable in r system command

I am trying to pass variable as an argument to system command in R.
> system("ls>abc.csv") #this works
> k<-"abc.csv"
> system("ls>k") #this does not work
> system2("ls>k") #this does not work
sh: ls>k: command not found
> system("ls>$k") #this does not work
sh: $k: ambiguous redirect
You can use paste to build the OS command and pass to system
system(paste("ls >", k))
The problem here is that R does not recognize variable k if you put it in a string.
But indeed it is very useful to put the file name in a variable if you want to use it again and again.
Can you try
system(paste0("ls>", k))
If this works, you can also write a small function:
"%&%" <- function(a, b)paste0(a, b)
And then you can do
system("ls>"%&%k)

How to program the computer to speak put loud in R

I have a script in R which returns a and I can print the result as
print(a)
Instead of print() I would like something like "speak()". So that the computer uses its "internal voice" and tells what the variable a is out loud.
Is this even possible in R?
(I use OSX)
(For example this "voice" can be heard in OSX when selecting a piece of text -> right-click -> speach -> begin speak.)
Problem solved!
As #Dason pointed out, it is possible to do a system call within R using system() and say as command.
The command in system() needs to be a complete string beginning with "say" and strings can be put together using sprintf().
Example:
a <- 2+5
b <- sprintf("say The result is %d", a)
system(b, intern = FALSE, ignore.stdout = FALSE, ignore.stderr =
FALSE, wait = TRUE, input = NULL)

Why is there an unexpected symbol in my R code?

I am not exactly sure what to change in my r code to remove the unexpected symbol.
Error: unexpected symbol in "LP=function(n1,n2,m2){N_hat_LP=(((n1)*(n2))/m2) return(N_hat_LP)}"
The problem is that you have the return command on the same line as the defining of N_hat_LP.
You could put the return(N_hat_LP) command on the next line.
In fact, you can simplify this greatly to just:
LP=function(n1,n2,m2){((n1)*(n2))/m2}
There's no point in defining N_hat_LP just to return it. R understands if you simply include what you want to do with the parameters.
You need to format your code. To prevent this, I recomment to read a style guide http://r-pkgs.had.co.nz/style.html. To solve the error, you can reformat:
LP <- function(n1, n2, m2) {
N_hat_LP <- n1 * n2 / m2
return(N_hat_LP)
}
Or leaf it in one line:
LP=function(n1,n2,m2){N_hat_LP=(((n1)*(n2))/m2);return(N_hat_LP)}

the difference between = and <- operator in the function system.time()

I am using the function system.time() and I have discovered something which surprises me. I often use the allocation symbol “=” instead of “<-”. I am aware most R users use “<-” but I consider “=” clearer in my codes. Thus, I used “=” to allocate a value in a function system.line() and the following error message appeared : Error: unexpected '=' in "system.time(a[,1] ="
Here is the code :
a = matrix(1, nrow = 10000)
require(stats)
system.time(a[,1] = a[,1]*2) #this line doesn't work
#Error: unexpected '=' in "system.time(a[,1] ="
system.time(a[,1] = a[,1]*2) #this line works
system.time(for(i in 1:100){a[,1] = a[,1]*i}) #this line works!!!!
I found : Is there a technical difference between "=" and "<-" which explains that I can’t use “=” in a function to allocate since it is the symbol to assign argument in a function. But I have been surprised to see that it can work sometimes (see following code).
Does anyone know why it works here? (also why it doesn't work in the first case since I guess, a[,1] is not a parameter of the function system.time()...)
Thank you very much.
Edwin.
Wrap your code in { ... } braces and it will work:
system.time({a[,1] = a[,1]*2})
user system elapsed
0 0 0
From ?"<-"
The operators <- and = assign into the environment in which they are
evaluated. The operator <- can be used anywhere, whereas the operator
= is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a
braced list of expressions.
In system.time(a[,1] = a[,1]*2) the equals sign does not mean assignment, it is interpreted as an attempt to bind a "named argument"; but system.time does not have an argument of that name.
In system.time(for(i in 1:100){a[,1] = a[,1]*i}) the equals sign really is doing an assignment; and that works fine.
If you wrote system.time(a[,1] <- a[,1]*2) the <- can only mean assignment, not argument binding, and it works!
But beware! If you wrote system.time(a[,1] < - a[,1]*2), it also "works" but probably doesn't do what you meant!

Debugging unexpected errors in R -- how can I find where the error occurred?

Sometimes R throws me errors such as
Error in if (ncol(x) != 2) { : argument is of length zero
with no additional information, when I've written no such code. Is there a general way for finding which function in which package causes an error?
Since most packages come compressed, it isn't trivial to grep /usr/lib/R/library.
You can use traceback() to locate where the last error occurred. Usually it will point you to a call you make in your function. Then I typically put browser() at that point, run the function again and see what is going wrong.
For example, here are two functions:
f2 <- function(x)
{
if (x==1) "foo"
}
f <- function(x)
{
f2(x)
}
Note that f2() assumes an argument of length 1. We can misuse f:
> f(NULL)
Error in if (x == 1) "foo" : argument is of length zero
Now we can use traceback() to locate what went wrong:
> traceback()
2: f2(x) at #3
1: f(NULL)
The number means how deep we are in the nested functions. So we see that f calls f2 and that gives an error at line 3. Pretty clear. We could reassign f with browser placed just before the f2 call now to check it's input. browser() simply allows you to stop executing a function and look around in its environment. Similar to debug and debugonce except that you don't have to execute every line up until the point you know something goes wrong.
Just to add to what #SachaEpskamp has already suggested, setting options(error=recover) and options(show.error.locations=TRUE) can be extremely helpful when debugging unfamiliar code. The first causes R to launch a debugging session on error, giving you the option to invoke the browser at any point in the call stack up to that error. The second option will tell R to include the source line number in the error.

Resources