您如何使用列名读取小标题中的单个单元格或为其赋值?

How do you read or assign a value to a single cell in a tibble, using the name of the column?

我正在将 tidyverse 和 运行 学习为最简单的 operations:reading 问题,并将值分配给单个单元格。我需要通过匹配另一列中的特定值并调用我想更改其值的列的名称来执行此操作(因此我不能使用数字行号和列号)。

我在网上和 SO 上搜索并阅读了 tibble 文档(这似乎是最适用的 https://tibble.tidyverse.org/reference/subsetting.html?q=cell),但没有找到答案。 (我可能遗漏了一些东西 - 对于这个问题的简单性以及是否在其他地方得到了回答,我深表歉意)

test<-tibble(x = 1:5, y = 1, z = x ^ 2 + y)

产量:

 A tibble: 5 x 3
      x     y     z
  <int> <dbl> <dbl>
1     1     1     2
2     2     1     5
3     3     1    10
4     4     1    17
5     5     1    26

test["x"==3,"z"]

产量:

 A tibble: 0 x 1
 … with 1 variable: z <dbl>

但没有告诉我该单元格的值。

当我尝试赋值时...

test["x"==3,"z"]<-20

...它不起作用。

test[3,3] 这可行,但如上所述,我需要按名称而不是数字来调用单元格。

正确的做法是什么?

这不是 data.table。如果我们使用 base R 方法,则使用 test$xtest[["x"]]

提取列 'x'
test[test$x == 3, "z"]
# A tibble: 1 x 1
#     z
#  <dbl>
#1    10

或使用subset

subset(test, x == 3, select = 'z')

或者用dplyr

library(dplyr)
test %>%
       filter(x == 3) %>%
       select(z)

或者如果我们想传递一个字符串作为列名,转换为 symbol 并求值

test %>% 
    filter(!!  rlang::sym("x") == 3) %>% 
    select(z)

或者用data.table

library(data.table)
as.data.table(test)[x == 3, .(z)]
#    z
#1: 10