I have written a function (pre_post_comparision
) that takes a set of columns containing survey responses, and uses a for
loop and a series of ifelse
statements to conditionally increment a score on a variable called bonus_points
.
The objective of the function is to return the bonus_points
column containing a user's score. bonus_points
should range between 0 and 3.
When running the function using the full dataset, the returned score has no variation, with a score of 2 for each user. When running the function one row at a same, I am able to achieve variation in the bonus_points
variable (i.e. bonus_points range between 0, 1, 2, 3).
What changes should I make to the function so that I am returning the correct bonus_points
score?
To help, below is an example of my code and dataset.
Thanks in advance!
The pre_post_comparison function
SEA_VALUE_LUT <- function(df){
for (i in 1:length(df)){
df[,i][df[i] == 4] <- 5
df[,i][df[i] == 3] <- 4
df[,i][df[i] == 2] <- 3
df[,i][df[i] == 0] <- 0
}
return(df)
}
pre_post_comparison <- function(df, cap){
df$bonus_points <- 0
for(i in seq(from=1, to=length(df)-2, by = 2)){
x <- as.data.frame(df[,i])
y <- as.data.frame(df[,i+1])
is_strength <- TRUE
pairs_df <- cbind(x, y)
pairs_df <- SEA_VALUE_LUT(pairs_df)
colnames(pairs_df) <- c("cur_value", "pre_value")
attach(pairs_df)
ifelse(cur_value >=3,
ifelse(is_strength && pre_value == 5,
df$bonus_points <- df$bonus_points + 1,
ifelse(!is_strength && pre_value == 0,
df$bonus_points <- df$bonus_points + 1,
ifelse(pre_value == 2 || pre_value == 3 || pre_value == 4,
df$bonus_points <- df$bonus_points + 1, NA))), NA)
detach(pairs_df)
}
df$bonus_points[df$bonus_points > cap] <- cap
return(df$bonus_points)
}
Example data frame
+--------------------+-------------------+--------------------+-------------------+------------------+-----------------+
| H.Response2.Attack | H.Response.Attack | H.Response2.Budget | H.Response.Budget | H.Response2.Cred | H.Response.Cred |
+--------------------+-------------------+--------------------+-------------------+------------------+-----------------+
| 4 | 4 | 4 | 4 | 4 | 3 |
| 4 | 4 | 3 | 2 | 3 | 4 |
| 4 | 4 | 3 | 2 | 3 | 4 |
| 4 | 4 | 4 | 4 | 4 | 4 |
+--------------------+-------------------+--------------------+-------------------+------------------+-----------------+
Aucun commentaire:
Enregistrer un commentaire