|
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 |
|
|
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.
All scalars in R are one-element vectors. Examples include f <- 3, g <- "US" and h <- TRUE.
Being a rather old language R ignores some of best practices of C language lexical structure and syntax:
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:
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:
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.
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
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
There are tree important built-in functions that are dealing with vectors:
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".
as.vector and is.vector are quite distinct from the meaning of the formal class "vector" in the methods package, and hence as(x, "vector") and is(x, "vector").
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.
From An Introduction to R
> 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.
> y <- x[-(1:5)]
gives y all but the first five elements of x.
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
The Vector
> v <- c(3,2,2) > v [1] 3 2 2Is Something A Vector
> is.vector(v) [1] TRUE > is.matrix(v) [1] FALSE"Transpose" of a Vector
> vp <- t(v) > vp [,1] [,2] [,3] [1,] 3 2 2Adding Vectors
> w <- c(4,1,2) > s <- v + w > s [1] 7 3 4Subtracting Vectors
> d <- v - w > d [1] -1 1 0Multiplication by a Scalar
> s <- 3*v > s [1] 9 6 6 > t <- v*3 > t [1] 9 6 6Vector Dot Product
> d <- v %*% w > d [,1] [1,] 18 > d <- w %*% v > d [,1] [1,] 18 > d <- v %*% v > d [,1] [1,] 17 > d <- w %*% w > d [,1] [1,] 21Length of a Vector
> a <- c(4,3) > a [1] 4 3 > sqrt(a %*% a) [,1] [1,] 5 > v [1] 3 2 2 > sqrt(v %*% v) [,1] [1,] 4.123106 > w [1] 4 1 2 > sqrt(w %*% w) [,1] [1,] 4.582576 # you can write a function to get the norm of a vector > normvec<-function(x) + {sqrt(x%*%x)} > normvec(v) [,1] [1,] 4.582576Unit Length Vector
> l <- c(1/2 , 1/2 , 1/2 , 1/2) > l [1] 0.5 0.5 0.5 0.5 > sqrt(l %*% l) [,1] [1,] 1The Unit Vector
> u <- c(1,1,1) > u [1] 1 1 1 > u %*% u [,1] [1,] 3 > v [1] 3 2 2 > u %*% v [,1] [1,] 7 > w [1] 4 1 2 > u %*% w [,1] [1,] 7
|
Switchboard | ||||
Latest | |||||
Past week | |||||
Past month |
I am new to R, and am trying to get my head around it, except I have a couple of questions:
- As the title says, what are the main differences between R vector and R list data types?
- Furthermore are there any advantages/dis advantages of these different data types?
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
activevotesTechnically 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) #TRUELists are a "recursive" type whereas atomic vectors are not:
is.recursive(aaa) # TRUE is.atomic(aaa) # FALSEYou 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 contentLists 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.htmlIt 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
Google matched content |
...
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 quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard 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 DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting 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-Month : How 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