DirtStats
DirtStats

Reputation: 599

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

I'm learning the tidyverse and ran into a problem with the simplest of operations:reading and assigning value to a single cell. I need to do this by matching a specific value in another column and calling the name of the column whose value I'd like to change (so I can't use numeric row and column numbers).

I've searched online and on SO and read the tibble documentation (this seems the most applicable https://tibble.tidyverse.org/reference/subsetting.html?q=cell) and haven't found the answer. (I'm probably missing something - apologies for the simplicity of this question and if it's been answered elsewhere)

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

Yields:

 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"]

Yields:

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

But doesn't tell me the value of that cell.

And when I try to assign a value...

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

...it does not work.

test[3,3] This works, but as stated above I need to call the cell by names not numbers.

What is the right way to do this?

Upvotes: 2

Views: 2732

Answers (1)

akrun
akrun

Reputation: 887621

It is not a data.table. If we are using base R methods, the columns 'x' is extracted with test$x or test[["x"]]

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

Or use subset

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

Or with dplyr

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

Or if we want to pass a string as column name, convert to symbol and evaluate

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

Or with data.table

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

Upvotes: 5

Related Questions