带有索引(短符号)的子集 tibble (tidyverse)
Subset tibble (tidyverse) with indexes (short notation)
我想从仅基于索引的 tibble tibble 中提取一个数值子集。例如,如果我想要第 2 行和第 3 列,我想使用 tibble[2,3]
。
然而这个returns一个tibble
而不是一个数字。
我知道可以使用 tibble[2,] %>% pull(3)
但是没有比 data.frame 更短的选项吗?
这里有两种方法。对于数据框或小标题,两者都同样有效。
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
我想从仅基于索引的 tibble tibble 中提取一个数值子集。例如,如果我想要第 2 行和第 3 列,我想使用 tibble[2,3]
。
然而这个returns一个tibble
而不是一个数字。
我知道可以使用 tibble[2,] %>% pull(3)
但是没有比 data.frame 更短的选项吗?
这里有两种方法。对于数据框或小标题,两者都同样有效。
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