Bart
Bart

Reputation: 317

R replace value in dataframe

I have a dataframe that has a few variables, datem, seriesid and price.

For a given seriesid e.g. series 1000 I want to change the price at a certain datem (note datem = year(date)*12 + month(date)).

I have tried:

df$price[df$seriesid==114051 & ((df$datem == (1888*12+4))||(df$datem==(1888*12+3)))] <- 10.0

However, this replaces all my datem values to the same datem and replaces all my seriesids with 114051.

Does anyone have an easy way to replace specific values within my dataframe (it is a large dataframe).

Thanks

Upvotes: 1

Views: 68

Answers (1)

linog
linog

Reputation: 6226

If your dataset is voluminous, data.table is a good option. You can use conditional replacement thanks to the := operator (update by reference)

library(data.table)
setDT(df)

df[id==114051 & (datem %in% c(1888*12+3, 1888*12+4))], price := 10.0]

The dplyr equivalent solution would be:

library(dplyr)
df %>% mutate(price = if_else(id==114051 & (datem %in% c(1888*12+3, 1888*12+4)), 10, price)

It is likely to be slower than the first solution

Upvotes: 2

Related Questions