【发布时间】:2019-01-22 18:20:29
【问题描述】:
我想仅基于索引从 tibble tibble 子集一个数值。例如,如果我想要第二行和第三列,我想使用tibble[2,3]。
但是,这会返回 tibble 而不是单个数字。
我知道可以使用 tibble[2,] %>% pull(3),但没有比 data.frame 方式更短的选项吗?
【问题讨论】:
标签: r dataframe dplyr tidyverse tibble
我想仅基于索引从 tibble tibble 子集一个数值。例如,如果我想要第二行和第三列,我想使用tibble[2,3]。
但是,这会返回 tibble 而不是单个数字。
我知道可以使用 tibble[2,] %>% pull(3),但没有比 data.frame 方式更短的选项吗?
【问题讨论】:
标签: r dataframe dplyr tidyverse tibble
这里有两种方法。无论是对数据帧还是对小标题都同样适用。
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 的描述以 “这类似于 [[ 用于本地数据帧...”开头。。