Search code examples
rvector

R: how to include a character between two repeted items in R?


I am new to R and have a few questions about vectors.

I need help creating a vector n containing two copies of vector x, separated by a 0.

I wrote the following code, but missing the ´0´part:

x<-c(3,10,30)


n=rep(x, times=2)

n

In addition, how to check if the content of two vectors is equal? And finally, how do I check for the length of a vector?


Solution

  • 1c: If you just need a 0 between two vectors, you can use the c() function to combine multiple objects together. In this case, we can make two copies of x with a 0 in-between them like so - c(x,0,x)

    2: R lets you check whether two things are equal in multiple ways. It sounds like your professor wants you to use the == approach, which checks if each element of two things are the same. As the next question notes though, doing that when they aren't the same length is possibly problematic - which element is the start, etc. Just something to be aware of. You can use if two things are identical though with identical()

    3: There is a function you can use for this. length() tells you how many elements are in an object. Just for fun, we can the == approach here to see if the lengths are equal (we know that R should tell use FALSE of course)

    x<-c(3,10,30)
    x
    
    m=rep(x, each=2)
    m
    
    n=rep(x, times=2)
    n
    
    # question 1c
    n <- c(x, 0, x)
    n
    
    # Question 2: Is the content of m equal to the content of n?
    n == m
    
    # Question 3: How can you check the length of both vectors?
    length(n)
    length(m)
    
    length(n) == length(m)