Hi I am supposed to create a function 'check_even' that accepts three arguments (1) ' df' a dataframe (2) ' col_test' to test if each row value in the indicated column is even or odd. Use for loop and nrow function. (3) ' col_multiply' the column to multiply by 2 if the 'col_test' is even and multiply by 3 if the 'col_test' is odd
- Store the result in a new column in the ' df' call ' res' and return the whole dataframe ' df'
- Test your function by running this code ' check_even(df_test, 'INT1', 'INT2')'
df_test = data.frame(INT1 = c(1:10), INT2 = (sample(x = c(20:100),size = 10, replace = F)))
df_test
check_even = function(df, col_test, col_multiply){
for(i in 1:nrow(df)){
if((df[,col_test[i]] %% 2) == 0){
df[,'res'] = (df[,col_multiply[i]] * 2)
} else
{
df[,'res'] = (df[,col_multiply[i]] * 3)
}
return(df) }
}
check_even(df_test, 'INT1', 'INT2')
I keep getting a result of all the values multiply by 3. Can I seek some help to see what is wrong with my codes?
Aucun commentaire:
Enregistrer un commentaire