2

I am new to R and I am trying to create simple UDFs in R. Every time I try to create one, I get the error "

Error: unexpected symbol in:".

Not sure where I am going wrong. Here are a few examples of the functions that I was creating

Function 1

addPercent <- function(x) {
   percent <- round (x *100, digits  = 1) result<- paste(percent, "%", sep="") return(result)
}

Function 2

avg<- function(x) { s <- sum(x) n <- length(x) s/n }

Would really appreciate any kind of help to solve this minor issue. Thank you much in advance

1
  • 3
    I'm not sure whether this is a formatting issue here on SO or if this is your actual issue; either use ; to separate multiple commands or use new lines. So avg should read avg <- function(x) { s <- sum(x); n <- length(x); s/n } Commented Mar 12, 2019 at 5:13

1 Answer 1

2

To expand from my comment:

In R you have to separate statements either with ; (semicolon) or with a newline.

So this works:

avg <- function(x) { s <- sum(x); n <- length(x); s/n }
avg(c(1, 2, 3))
#[1] 2

As does this

avg <- function(x) { 
    s <- sum(x)
    n <- length(x)
    s/n 
}
avg(c(1, 2, 3))
#[1] 2

To pre-empt the question "What's the difference?", see the following post: What's the difference in using a semicolon or explicit new line in R code .

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.