简体   繁体   中英

How to apply a formula to a part of an R dataframe column?

How should I modify a part of a single data frame column in R?

I have a data frame having several columns of which I need only the Date column and the relevant variable (named RIL0). I simply want to double the values in the RIL0 column a certain date (26-Nov-2009) onward but I can't find a way to get it done.

a <- read.csv("<Some file>.csv", header = TRUE, sep = ",") # loaded csv file
a$Date <- as.Date(a$Date, "%d-%b-%Y") # date formatted
a <- a[,-c(2,3)] # retained only the Date and RIL0 columns
head(a)

        Date    RIL0
1 2009-07-01 2057.35
2 2009-07-02 2010.15
3 2009-07-03 2025.85
4 2009-07-06 1893.60

I tried splitting the column into 2 halves and then rejoining them after doubling one of them but it did not work.

If your Date column is ordered, you can try

inds <- a$Date > as.Date("2009-11-26")
a$RIL0[inds] <- a$RIL0[inds] * 2

If it is not ordered and you want to change all the values which occur after the date try

inds <- which(a$Date == as.Date("2009-11-26"))
a$RIL0[inds : nrow(a)] <- a$RIL0[inds : nrow(a)] * 2

This is assuming your Date column is of "Date" class. If it is of factor or character class first run

a$Date <- as.Date(a$Date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM