Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

R Vectors

News Scripting languages R Bookshelf Recommended Links KISS Principle An Introduction to R R Style Guide
R data types Vectors Factors R Data Frames Matrices I/O Functions
Rstudio R Debugging General principles of debugging R help system R-Studio Keyboard Shortcuts R Environment Variables  
R Packages CRAN package repository Quantmod package TTR Package Zoo package ggplot2 package  
Brooks law  Conway Law Code Reviews and Inspections Code Metrics Software Engineering Programming style  
Software Fashion   Tips Quotes R history Humor Etc

Introduction

Vectors in R are one dimensional collections that like in C and Fortran store one type of data (Numbers, strings, logical values, etc). Vector is an ordered sequence of elements with no other structure. The length of a vector is the number of elements.  Like in Fortran, indices in R start at 1, not at 0 like in C-derived languages such as Perl.

So x[1] is the first element of vector x. The type of a vector must be one of the following: logical, integer, double, complex, character, or raw. All elements of a vector must have the same underlying type.

Operations are applied component wise using implicit loop. For example, given two vectors x and y of equal length, x+y would be the vector whose nth component is the sum of the nth components of x and y. Similarly, log(x) would be the vector whose nth component is the logarithm of the nth component of x.

mean(newVector) will get you a new vector with dimension one containing  the average.

Note:

All scalars in R are one-element vectors. Examples include f <- 3, g <- "US" and h <- TRUE.

Variable names gotchas

Being a rather old language R ignores some of best practices of C language lexical structure and syntax:

  1. Initially the underscore was not allowed as a variable character in R. It is now allowed, but there is already strong tradition/convention to use dot instead of underscore. The dot character in R has no special significance. It is just a part of identifier character set, like letter "a". 
  2. R uses $ in a manner analogous to the way other languages use dot.
  3. R has several one-letter reserved words (used mostly for names of built-in functions): c, q, s, t, C, D, F, I, and T. For example, c is a built-in function for creating vectors (see below)

c function

Vectors can be created from scalar data using the c  function. For example, p <- c(2,3,5,7)  sets p  to the vector containing the first four prime numbers.

Vectors  can hold only one type of data (all elements should belong to the same type). Any type can be used. For example you can create numeric vector, vector of strings of character, or vector that contain logical values.  Here are examples of each type of vector:

a <- c(1, 2, 5, 3, 6, -2, 4)
b <- c("one", "two", "three")
c <- c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE)

Displaying values of vector is easy:

Generation of simple sequences

The expression seq(a, b, n)  creates a vector that contain interval from a  to b  in steps of size n. For example, seq(1, 10, 3)  returns the vector containing 1, 4, 7, and 10. This is similar to range(a, b, n)  in Python, except Python uses half-open intervals and so the 10 would not be included in this example. The step (increment) argument n  defaults to 1 in both R and Python.

Arguments to seq(), and to many other R functions, can also be given in named form, in which case the order in which they appear is irrelevant. The first two arguments may be named from=value  and to=value; thus seq(1,30), seq(from=1, to=30)  and seq(to=30, from=1)  are all the same as 1:30. The next two arguments to seq()  may be named by=value  and length=value, which specify a step size and a length for the sequence respectively. If neither of these is given, the default by=1  is assumed.

For example

> seq(-5, 5, by=.2) -> s3

generates in s3  the vector c(-5.0, -4.8, -4.6, ..., 4.6, 4.8, 5.0). Similarly

> s4 <- seq(length=51, from=-5, by=.2)

generates the same vector in s4.

The fifth argument may be named along=vector, which is normally used as the only argument to create the sequence 1, 2, ..., length(vector), or the empty sequence if the vector is empty (as it can be).

A related function is rep()  which can be used for replicating an object in various complicated ways. The simplest form is

> s5 <- rep(x, times=5)

which will put five copies of x  end-to-end in s5. Another useful version is

> s6 <- rep(x, each=5)

which repeats each element of x  five times before moving on to the next.

Notes:

Entering values from the console

You can add items from command line with the function scan:

newVector = scan()
1: 10 20 30 35 12 23 12

The scan() function will put all the items into newVector. This function may be handy to copy and paste a long list of numbers from an other document to R without the need to type them. You can mix manual entry and paste operations. The input operation will be closed when you press 2 times enter when the last item is added. 

Examples of access to elements

You can refer to elements of a vector using a constant, or a numeric vector of positions within brackets. The following examples show how to retrieve specific values from the recently made vector.

This is pretty similar to what we have in other scripting languages. But there much less understandable operations. for example to select elements from a vector you can write something like: 

newVector < 20 # gives all the elements smaller then 20.  

This is like implicit map function invocation with appropriate condition.

Here are additional examples:

> a <- c(1, 2, 5, 3, 6, -2, 4)
> a[3]
[1] 5
> a[c(1, 3, 5)]
[1] 1 5 6
> a[2:6]
[1]  2  5  3  6 -2

Recycling Rule

If two vectors are of unequal length, the shorter one will be recycled in order to match the longer vector. For example, the following vectors u and v have different lengths, and their sum is computed by recycling values of the shorter vector u.

> u = c(10, 20, 30)  
> v = c(1, 2, 3, 4, 5, 6, 7, 8, 9)  
> u + v  
> [1] 11 22 33 14 25 36 17 28 39

Functions vector, as.vector and is.vector

There are tree important built-in functions that are dealing with vectors:

  1. vector  produces a vector of the given length and mode.  Logical vector elements are initialized to FALSE, numeric vector elements to 0, character vector elements to "", raw vector elements to nul  bytes and list/expression elements to NULL.

  2. as.vector, a generic, attempts to coerce its argument into a vector of mode mode  (the default is to coerce to whichever vector mode is most convenient): if the result is atomic all attributes are removed.  All attributes are removed from the result if it is of an atomic mode, but not in general for a list result. The default method handles 24 input types and 12 values of type: the details of most coercions are undocumented and subject to change.

  3. is.vector  returns TRUE  if x  is a vector of the specified mode having no attributes other than names. It returns FALSE  otherwise. For is.vector, TRUE  or FALSE. is.vector(x, mode = "numeric")  can be true for vectors of types "integer"  or "double"  whereas is.vector(x, mode = "double")  can only be true for those of type "double".
    vector(mode = "logical", length = 0)
    as.vector(x, mode = "any")
    is.vector(x, mode = "any")

Arguments

 The atomic modes are "logical", "integer", "numeric"  (synonym "double"), "complex", "character"  and "raw".

If mode = "any", is.vector  may return TRUE  for the atomic modes, list  and expression. For any mode, it will return FALSE  if x  has any attributes except names. (This is incompatible with S.) On the other hand, as.vector  removes all attributes including names for results of atomic mode (but not those of mode "list"  nor "expression").

Note that factors are not vectors; is.vector  returns FALSE  and as.vector  converts a factor to a character vector for mode = "any".

Notes:

Examples

df <- data.frame(x = 1:3, y = 5:7)
## Error:
try(as.vector(data.frame(x = 1:3, y = 5:7), mode = "numeric"))

x <- c(a = 1, b = 2)
is.vector(x)
as.vector(x)
all.equal(x, as.vector(x)) ## FALSE


###-- All the following are TRUE:
is.list(df)
! is.vector(df)
! is.vector(df, mode = "list")

See Also c, is.numeric, is.list, etc.

Obtaining a subset of the vector

From An Introduction to R

  1. Selecting a subset of a vector using as index a vector containing positive integers. In this case the values in the index vector must lie in the set {1, 2, …, length(x)}. The corresponding elements of the vector are selected and concatenated, in that order, in the result. The index vector can be of any length and the result is of the same length as the index vector. For example x[6]  is the sixth component of x  and
    > x[1:10]
    

    selects the first 10 elements of x  (assuming length(x)  is not less than 10). Also

    > c("x","y")[rep(c(1,2,2,1), times=4)]
    

    (an admittedly unlikely thing to do) produces a character vector of length 16 consisting of "x", "y", "y", "x"  repeated four times.
     

  2. Selecting a subset of a vector using as index a vector with negative integers. Such an index vector specifies the values to be excluded rather than included. Thus
    > y <- x[-(1:5)]
    

    gives y  all but the first five elements of x.

Reference

 Vector functions used in R.

Operation Meaning
max(x) maximum value in x
min(x) minimum value in x
sum(x) total of all the values in x
mean(x) arithmetic average of the values in x
median(x) median value in x
range(x) vector of min(x) and max(x)
var(x) sample variance of x
cor(x,y) correlation between vectors x and y
sort(x) a sorted version of x
rank(x) vector of the ranks of the values in x
order(x) an integer vector containing the permutation to sort x into ascending order
quantile(x) vector containing the minimum, lower quartile, median, upper quartile, and maximum of x
cumsum(x) vector containing the sum of all of the elements up to that point
cumprod(x) vector containing the product of all of the elements up to that point
cummax(x) vector of non-decreasing numbers which are the cumulative maxima of the values in x up to that point
cummin(x) vector of non-increasing numbers which are the cumulative minima of the values in x up to that point
pmax(x,y,z) vector, of length equal to the longest of x, y or z, containing the maximum of x, y or z for the ith position in each
pmin(x,y,z) vector, of length equal to the longest of x, y or z, containing the minimum of x, y or z for the ith position in each
colMeans(x) column means of dataframe or matrix x
colSums(x) column totals of dataframe or matrix x
rowMeans(x) row means of dataframe or matrix x
rowSums(x) row totals of dataframe or matrix x

From Vector Operations in R

The Vector

Is Something A Vector

"Transpose" of a Vector

Adding Vectors

Subtracting Vectors

Multiplication by a Scalar

Vector Dot Product

Length of a Vector

Unit Length Vector

The Unit Vector

 


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

What are the differences between R vector and R list data types

I am new to R, and am trying to get my head around it, except I have a couple of questions:

I am trying to think of examples that demonstrate each of the data types well, in an actual scenario where they might be employed but am having difficulty. So help on this would also be appreciated.

If anyone could point me in the right direction with regard the solutions to the above question I would very much appreciate it.

===

I'm not sure you can delete a question that has upvoted answers. What you are now doing is defacing what several people thought had useful replies. I'm going to flag it. – BondedDust Jan 16 '12 at 17:45

activevotes

Technically lists are vectors, although very few would use that term. "list" is one of several modes, with others being "logical", "character", "numeric", "integer". What you are calling vectors are "atomic" in strict R parlance:

 aaa <- vector("list", 3) is.list(aaa) #TRUE is.vector(aaa) #TRUE

Lists are a "recursive" type whereas atomic vectors are not:

is.recursive(aaa) # TRUE is.atomic(aaa) # FALSE

You process data objects with different functions depending on whether they are recursive, atomic or have dimensional attributes (matrices and arrays). However, I'm not sure that a discussion of the "advantages and disadvantages" of different data structures is a sufficiently focused question for SO. To add to what Tommy said, besides lists being capable of holding an arbitrary number of other vectors there is the availability of dataframes which are a particular type of list that has a dimensional attribute which defines its structure. Unlike matrices and arrays which are really folded atomic objects, dataframes can hold varying types including factor types.

===

There is a typo in the code. The is.recursive(aa) should be is.recursive(aaa). Could you please fix it? – zyl1024 Nov 16 '14 at 16:00

As @DWin explained, lists are "recursive". This means that they can contain values of different types, even other lists:

x <- list(values=sin(1:3), ids=letters[1:3], sub=list(foo=42,bar=13)) x # print the list x$values # Get one element x[["ids"]] # Another way to get an element x$sub$foo # Get sub elements x[[c(3,2)]] # Another way (gets 13) str(x) # A "summary" of the list's content

Lists are used in R to represent data sets: the data.frame class is essentially a list where each element is a column of a specific type.

Another use is when representing a model: the result from lm returns a list that contains a bunch of useful objects.

d <- data.frame(a=11:13, b=21:23) is.list(d) # TRUE str(d) m <- lm(a ~ b, data=d) is.list(m) # TRUE str(m)

...And atomic vectors (non-lists like numeric, logical and character) are useful since all elements are known to have the same type. This makes manipulating them very fast.

This and similar introductory questions are answered in http://www.burns-stat.com/pages/Tutor/hints_R_begin.html

It is meant to be a gentle introduction that gets you up and running with R as quickly as possible. To some extent it succeeds.

As someone who's just gotten into R, but comes from a C/Java/Ruby/PHP/Python background, here's how I think of it.

A list is really an array + a hashmap. It's a PHP associative array.

> foo = list(bar='baz') > foo[1] 'baz' > foo$bar 'baz' > foo['bar'] 'baz'

A vector is a fixed-type array/list. T

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

Top articles

Sites

...

R programming tutorial - Vector Objects in R - Quick video on Vector Coercion - Programming in R - YouTube



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: October, 16, 2019