How to initialize a vector with fixed length in R

How to initialize a vector with fixed length in R ??

For example, I want a vector of characters with length of 10??

Answers


?vector

X <- vector(mode="character", length=10)

This will give you empty strings. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be dissappointed.

>  X[5] <- "character element in 5th position"

>  X
 [1] ""                                  ""                                 
 [3] ""                                  ""                                 
 [5] "character element in 5th position" ""                                 
 [7] ""                                  ""                                 
 [9] ""                                  "" 
>  nchar(X)
 [1]  0  0  0  0 33  0  0  0  0  0

> length(X)
[1] 10

If you want to initialize a vector with numeric values other than zero, use rep

n <- 10
v <- rep(0.05, n)
v

which will give you:

[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

The initialization method easiest to remember is

vec = vector(,10); #the same as "vec = vector(length = 10);"

The values of vec are: "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE" (logical mode) by default.

But after setting a character value, like

vec[2] = 'abc'

vec becomes: "FALSE" "abc" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"", which is of the character mode.


Just for the sake of completeness you can just take the wanted data type and add brackets with the number of elements like so:

x <- character(10)


Need Your Help

How to set the HTTP Keep-Alive timeout in a nodejs server

node.js http-headers express keep-alive

I'm actually doing some load testing against an ExpressJS server, and I noticed that the response send by the server includes a "Connection: Keep-Alive" header. As far as I understand it, the conne...