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?
CodePudding user response:
Try simpler solution with ifelse
:
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)){
df$res = ifelse(df[,col_test[i]] %% 2 == 0, df[,col_multiply[i]] * 2, df[,col_multiply[i]] * 3)
return(df)}
}
check_even(df_test, 'INT1', 'INT2')
CodePudding user response:
You may try
check_even = function(df, col_test, col_multiply){
res <- c()
for(i in 1:nrow(df)){
if((df[i,col_test] %% 2) == 0){
res = c(res,df[i,col_multiply] * 2)
} else
{
res = c(res,df[i,col_multiply] * 3)
}
}
df$res <- res
return(df)
}
check_even(df_test, 'INT1', 'INT2')
INT1 INT2 res
1 1 61 183
2 2 88 176
3 3 85 255
4 4 95 190
5 5 81 243
6 6 83 166
7 7 70 210
8 8 37 74
9 9 29 87
10 10 91 182
Or using dplyr
, it do not need any for loop
library(dplyr)
check_even = function(df, col_test, col_multiply){
df %>%
mutate(res = ifelse({{col_test}} %% 2 == 0, {{col_multiply}} * 2, {{col_multiply}} * 3))
}
check_even(df_test, INT1, INT2)
INT1 INT2 res
1 1 61 183
2 2 88 176
3 3 85 255
4 4 95 190
5 5 81 243
6 6 83 166
7 7 70 210
8 8 37 74
9 9 29 87
10 10 91 182