R Lang

R Program to Add Two Vectors3 min read

Example 1, Here is an example of an R program that adds two vectors and prints the result:

The output of this program would be:




This program defines two vectors, v1 and v2, and assigns them the values 1, 2, 3, 4 and 5, 6, 7, 8, respectively. It then adds the vectors using the + operator and stores the result in a new vector v3. Finally, it prints the contents of v3 to the console using the print() function.

Example 2, Here is an example of an R program that prompts the user to enter two vectors and then adds them:

This program reads the vectors from the user using the readline() function and stores them in the variables v1 and v2. It then converts the strings that are read from the user into numeric vectors using the as.numeric() function.

Next, it adds the vectors using the + operator and stores the result in a new vector v3. Finally, it prints the contents of v3 to the console using the print() function.

Here is an example of what the output of this program might look like:

Example 3, Here is an example of an R program that reads two vectors from a file and then adds them:

This program reads the vectors from the files “vector1.txt” and “vector2.txt” using the scan() function and stores them in the variables v1 and v2, respectively.

Next, it adds the vectors using the + operator and stores the result in a new vector v3. Finally, it prints the contents of v3 to the console using the print() function.

The vectors in the input files should be formatted as one element per line, like this:

Example 4, It is not possible to directly mix R and Python code in a single program. However, it is possible to call R code from within a Python program using the rpy2 library.

Here is an example of a Python program that calls an R function to add two vectors:

This program uses the rpy2 library to call an R function to add the vectors v1 and v2, which are defined in Python using the IntVector class from rpy2. The result of the addition is stored in the variable v3, which is also defined in Python. Finally, the program prints the contents of v3 to the console.

The output of this program would be:

Leave a Comment