Date handling with lubridate and if-statement

I am struggling with some data manipulation. One of the columns in my data sheet contains the date of birth, but for one location, the values ​​are disabled for 100 years.

I gave an example of a small data frame to explain my problem: the dates for Paris / Berlin are correct, I want to change the date only for those lines with London as a place (for this example, from 2028-3-25 to 1928 -3-25).

library(lubridate)
date <- as.Date(c('1950-11-1','2028-3-25','1940-3-14'))
location <- c("Paris", "London", "Berlin")
df <- data.frame(date, location)
df$date_new <- ifelse(df$location %in% c("London"), df$date - years(100), df$date)

As you can see, I installed the lubridate package and tried using the if else statement, but that just gives me negative numbers in the new column.

The solution is probably very simple, but I can't figure it out, and it drives me crazy.

Thank!

+4
2

df$date_new <- df$date
df$date_new[df$location=="London"] <- df$date_new[df$location=="London"] - years(100)

df$date_new <- ifelse(df$location %in% c("London"), df$date - years(100), df$date)

df$date_new <- ifelse(df$location %in% c("London"), as.character(df$date - years(100)), as.character(df$date))
+4

ifelse :

(. ), (. oldClass) , .

, ​​

(tmp <- yes; tmp[!test] <- no[!test]; tmp), , .

ifelse. :

> df$date_new = df$date
> df[location == "London",]$date_new = df[location == "London",]$date_new - years(100)
> df
        date location   date_new
1 1950-11-01    Paris 1950-11-01
2 2028-03-25   London 1928-03-25
3 1940-03-14   Berlin 1940-03-14

, ifelse, , ( R)

> library(lubridate)
> date <- as.Date(c('1950-11-1','2028-3-25','1940-3-14'))
> location <- c("Paris", "London", "Berlin")
> df <- data.frame(date, location)
> df$date_new <- as.Date(ifelse(df$location == "London", as.Date(df$date - years(100)), df$date), origin = origin)
> df
        date location   date_new
1 1950-11-01    Paris 1950-11-01
2 2028-03-25   London 1928-03-25
3 1940-03-14   Berlin 1940-03-14
+3

Source: https://habr.com/ru/post/1663866/


All Articles