【问题标题】:Subset tibble (tidyverse) with indexes (short notation)带有索引(短符号)的子集 tibble (tidyverse)
【发布时间】:2019-01-22 18:20:29
【问题描述】:

我想仅基于索引从 tibble tibble 子集一个数值。例如,如果我想要第二行和第三列,我想使用tibble[2,3]

但是,这会返回 tibble 而不是单个数字。

我知道可以使用 tibble[2,] %>% pull(3),但没有比 data.frame 方式更短的选项吗?

【问题讨论】:

    标签: r dataframe dplyr tidyverse tibble


    【解决方案1】:

    这里有两种方法。无论是对数据帧还是对小标题都同样适用。

    library(tibble)
    x = as_tibble(mtcars)
    ## The problem
    x[1, 1]
    ##  A tibble: 1 x 1
    #     mpg
    #   <dbl>
    # 1    21
    
    ## Solution 1: [.data.frame has drop = TRUE by default. Tibble switches
    ## the default to drop = FALSE, but you can still use the argument:
    x[1, 1, drop = TRUE]
    # [1] 21
    
    ## Solution 2: Use [[ to get a single column as a vector, and [ to
    ## pull the element you want
    x[[1]][1]
    [1] 21
    

    【讨论】:

    • 谢谢,我不知道双方括号的选项
    • pull 只是[[ 的“管道”版本。 ?pull 的描述以 “这类似于 [[ 用于本地数据帧...”开头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2015-12-02
    • 2016-11-04
    • 2015-12-11
    相关资源
    最近更新 更多