hat6ytrs
hat6ytrs

Reputation: 21

How to replace multiple values in a dataframe column with another value?

I have a dataframe with a structure like this.

head(df,n=5)
    Var1 Var2 Var3 value
1    1    1    1    NA
2    2    1    1    NA
3    3    1    1    NA
4    4    1    1    NA
5    5    1    1    NA

var3 as shown has value 1 for some rows(~500), 2 for some and so on till 366. I have a Date type stored with dates in the form

 head(date,n=5)
  "2020-01-01" "2020-01-02" "2020-01-03" "2020-01-04" "2020-01-05"

what I want to achieve is to replace var3 variable with dates as it represents the layer of the multidimensional array. i.e replace all 1 value with 2020-01-01, 2 with 2020-01-02 and so on. essentially making the df into the following

    Var1 Var2 Var3         value
1    1    1    2020-01-01    NA
2    2    1    2020-01-01    NA
3    3    1    2020-01-01    NA
4    4    1    2020-01-01    NA
5    5    1    2020-01-01    NA

how should I approach this issue?

Upvotes: 0

Views: 116

Answers (1)

Jc Bodoque
Jc Bodoque

Reputation: 11

you can replace var3 by adding var3 and a fixed date point. Using tidyverse, it looks like:

df <- df %>% mutate(var3=as.Date(var3, origin = "2019-12-31"))

that means var3 (numbers) is considered as days after 2019/dec/31

Upvotes: 1

Related Questions