Search code examples
rvectorappendr-factor

How do I append an int vector to a factor?


I have a matrix called matrix that looks like this:

charge  convexhull_xCoor    convexhull_yCoor    id              intensity
3       3336.43             667.62       f_7936733956214261295  475891
3       3339.73             667.6        f_7936733956214261295  475891

I get two vectors, id and intensity:

idVector = matrix[4]
intensityVector = matrix[5]

I want to add these two vectors together using append:

bigVector = append(idVector, intensityVector)

However, when I do this I get this as a result:

[1]       4       3       2       1  475891 5490000 1860000 1100000

R made a class = factor out of the idVector and when I appends the intVector to it, it is not appending it to the labels. How can I append an int vector to a factor?

Below is the reproducible code, I only have trouble giving the dput(head(matrix,4)) because it gives all the id's which are quite a lot, I gave the dput(head(matrix,4)) of the vectors instead.

vector1 = structure(c(4L, 3L, 2L, 1L), .Label = c("f_15177294341548527346", "f_18178836531573487427", "f_2444900193131259878", "f_7936733956214261295"), class = factor")
vector2 = c(475891, 5490000, 1860000, 1100000)
bigVector = append(vector1, vector2)
vector1
vector2
bigVector

Solution

  • You can't mix factors & numbers like that in a vector - you have to use a data frame.

    bigdf <- data.frame( id=idVector, intensity=intensityVector )
    

    Then have a look at bigdf (and you can access columns via bigdf$id, etc).

    Alternatively, if the elements of idVector are unique, you could add idVector as the names attribute of your intensityVector:

    names(intensityVector) <- idVector
    

    However the id is no longer a factor, but you can refer to values in intensity by a particular id as in intensityVector['f_7936733956214261295'].

    The data frame approach is almost always better because it's very well-suited to statistical analysis.