How to access single elements in a table in R

后端 未结 3 622
梦谈多话
梦谈多话 2020-12-23 20:52

How do I grab elements from a table in R.

My Data looks like this:

         V1     V2
1      12.448 13.919
2      22.242  4.606
3           


        
相关标签:
3条回答
  • 2020-12-23 21:18

    Maybe not so perfect as above ones, but I guess this is what you were looking for.

    data[1:1,3:3]    #works with positive integers
    data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
    data[i:i,j:j]    #given that i and j are positive integers
    

    Here indexing will work from 1, i.e,

    data[1:1,1:1]    #means the top-leftmost element
    
    0 讨论(0)
  • 2020-12-23 21:19

    That is so basic that I am wondering what book you are using to study? Try

    data[1, "V1"]  # row first, quoted column name second, and case does matter
    

    Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.

    I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html

    0 讨论(0)
  • 2020-12-23 21:25

    ?"[" pretty much covers the various ways of accessing elements of things.

    Under usage it lists these:

    x[i]
    x[i, j, ... , drop = TRUE]
    x[[i, exact = TRUE]]
    x[[i, j, ..., exact = TRUE]]
    x$name
    getElement(object, name)
    
    x[i] <- value
    x[i, j, ...] <- value
    x[[i]] <- value
    x$i <- value
    

    The second item is sufficient for your purpose

    Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

    So these work:

    data[1,1]
    data[1,"V1"]
    

    As does this:

    data$V1[1]
    

    and keeping in mind a data frame is a list of vectors:

    data[[1]][1]
    data[["V1"]][1]
    

    will also both work.

    So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

    0 讨论(0)
提交回复
热议问题