Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

populate new columns using formulas of previous column

$
0
0

I have a data frame of 2 columns (stage, year2000) and 6 rows as shown. stage (A,B,C,D,E,F), year2000 (100, 120, 90, 80, 70, NA)

I added a new column "year2001" using the R codes below:

data$year2001 <- ifelse(data$stage=="A", data$year2000*0.1, 
              ifelse(data$stage=="B", lag(data$year2000, 1)*0.9+data$year2000*0.2, 
               ifelse(data$stage=="C", lag(data$year2000, 1)*0.8+data$year2000*0.3,
                ifelse(data$stage=="D", lag(data$year2000, 1)*0.7+data$year2000*0.4,
                 ifelse(data$stage=="E", lag(data$year2000, 1)*0.6+data$year2000*0.5,
                  ifelse(data$stage=="F", lag(data$year2000, 1)*0.5,NA))))))

This means e.g.: stageC_year2001 is the sum of stageB_year2000*0.8 and stageC_year2000*0.3

My question is how to automatically populate more columns in R (like "auto fill" function in excel), "year2002, year2003, year2004 and so on", using the same formula by which year2001 column is created, value in each new column is computed using the column to its left.

Many thanks!

dataframe


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>