简体   繁体   中英

Change column values based on factors of other columns

For example, if I have a data frame like this:

df <- data.frame(profit=c(10,10,10), year=c(2010,2011,2012))

profit     year  
10         2010  
10         2011  
10         2012 

I want to change the value of profit according to the year . For year 2010, I multiple the profit by 3, for year 2011, multiple the profit by 4, for year 2012, multiple by 5, which should result like this:

profit     year  
30         2010  
40         2011  
50         2012 

How should I approach this? I tried:

inflationtransform <- function(k,v) {
    switch(k, 
        2010,v<-v*3,
        2011,v<-v*4,
        2012,v<-v*5,
    )
}

df$profit <- sapply(df$year,df$profit,inflationtransform)

But it doesn't work. Can someone tell me what to do?

For this particular example, since your factors and years are both ordered and incremented by 1, you could just subtract 2007 from the year column and multiply it by profit .

transform(df, profit = profit * (year - 2007))
#   profit year
# 1     30 2010
# 2     40 2011
# 3     50 2012 

Otherwise, you could use a lookup vector. This will cover all cases.

lookup <- c("2010" = 3, "2011" = 4, "2012" = 5)
transform(df, profit = profit * lookup[as.character(year)])
#   profit year
# 1     30 2010
# 2     40 2011
# 3     50 2012

I wouldn't use switch() unless you really need to. It's not vectorized, and that's where R is most efficient. However, since you ask for it in the comments, here's one way. I find it easier to use a for() loop with switch() .

for(i in seq_len(nrow(df))) {
    df$profit[i] <- with(df, switch(as.character(year[i]),
        "2010" = 3 * profit[i],
        "2011" = 4 * profit[i],
        "2012" = 5 * profit[i]
    ))
}

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