How to create an empty R vector to add new items

前端 未结 7 822
再見小時候
再見小時候 2020-12-07 10:42

I want to use R in Python, as provided by the module Rpy2. I notice that R has very convenient [] operations by which you can extract the specific columns or li

相关标签:
7条回答
  • 2020-12-07 11:13

    As pointed out by Brani, vector() is a solution, e.g.

    newVector <- vector(mode = "numeric", length = 50)

    will return a vector named "newVector" with 50 "0"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.

    aVector <- c(aVector, newScalar)

    0 讨论(0)
  • 2020-12-07 11:18

    In rpy2, the way to get the very same operator as "[" with R is to use ".rx". See the documentation about extracting with rpy2

    For creating vectors, if you know your way around with Python there should not be any issue. See the documentation about creating vectors

    0 讨论(0)
  • 2020-12-07 11:19

    To create an empty vector use:

    vec <- c();
    

    Please note, I am not making any assumptions about the type of vector you require, e.g. numeric.

    Once the vector has been created you can add elements to it as follows:

    For example, to add the numeric value 1:

    vec <- c(vec, 1);
    

    or, to add a string value "a"

    vec <- c(vec, "a");
    
    0 讨论(0)
  • 2020-12-07 11:26
    vec <- vector()
    

    See also vector help

    ?vector
    
    0 讨论(0)
  • 2020-12-07 11:29

    You can create an empty vector like so

    vec <- numeric(0)
    

    And then add elements using c()

    vec <- c(vec, 1:5)
    

    However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements)

    0 讨论(0)
  • 2020-12-07 11:29

    I've also seen

    x <- {}
    

    Now you can concatenate or bind a vector of any dimension to x

    rbind(x, 1:10)
    cbind(x, 1:10)
    c(x, 10)
    
    0 讨论(0)
提交回复
热议问题