# Go through an R dataframe and increase the salary at certain conditions

3870 views
2

I have this sample of my dataframe (df):

``````   age  salary
1  25   20000
2  35   22000
3  31   23500
4  24   19200
5  27   27900
6  32   31010
``````

I want to increase the salary by 11% for people who are aged above 30 and their salary is not the maximum salary in the table. I wrote this loop:

``````for(row in df){
if (row\$age > 30 & row\$salary != max(df\$salary)){
row\$salary = row\$salary * 0.11
}
}
``````

but I get less than the salaries posted rather than an increase.

Would really appreciate any help.

Sorry, just updated that. Thanks.

4

The reason why you're experiencing problems is because in each iteration of the for loop (specifically, when going through each matching row), you're applying a transformation to the entire column. Try this instead:

``````k <- max(df\$age)
df[df\$age>30 & df\$age<k, 'salary'] <- df[df\$age>30 & df\$age<k, 'salary'] * 1.11
``````

posted this
4

You should add the salary to the 0.11 * salary. And, you don't really need a loop to do that. Look at this:

``````df\$salary <- ifelse(df\$age > 30 & df\$salary != max(df\$salary), df\$salary+(df\$salary*0.11), df\$salary)
``````

Hope that helps.

posted this