Lotus@ 2009-07-23 03:33 采纳率: 100%
浏览 430
已采纳

方括号[]和双括号[[]之间的差异,用于访问列表或数据文件的元素

R provides two different methods for accessing the elements of a list or data.frame- the [] and [[]] operators.

What is the difference between the two? In what situations should I use one over the other?

转载于:https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-elem

  • 写回答

11条回答 默认 最新

  • 北城已荒凉 2009-07-23 03:46
    关注

    The R Language Definition is handy for answering these types of questions:

    R has three basic indexing operators, with syntax displayed by the following examples

        x[i]
        x[i, j]
        x[[i]]
        x[[i, j]]
        x$a
        x$"a"
    

    For vectors and matrices the [[ forms are rarely used, although they have some slight semantic differences from the [ form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, x[[i]] or x[i] will return the ith sequential element of x.

    For lists, one generally uses [[ to select any single element, whereas [ returns a list of the selected elements.

    The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?