Recap - Sigma Function
Part of the Fundamentals section of Coddy's R journey — lesson 49 of 78.
Challenge
EasyCreate a function called sigma that takes one argument n and returns the sum of all integers from 1 to n.
Read a number from input, convert it to a numeric value, and call your sigma function with this value. Print the returned result.
For example, if the input is 5, your function should calculate 1 + 2 + 3 + 4 + 5 = 15, and the output should be:
[1] 15If the input is 10, your function should calculate the sum from 1 to 10, and the output should be:
[1] 55If the input is 1, the output should be:
[1] 1Try it yourself
# Read input
con <- file("stdin", "r")
n <- suppressWarnings(readLines(con, n = 1))
n <- as.numeric(n)
# TODO: Create a function called 'sigma' that takes one argument 'n'
# and returns the sum of all integers from 1 to n
# Call the function and print the result
print(sigma(n))All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values