I tried to replace the names of the 'Level' values in the column 'variable' with an if-then statement, so that I can eventually turn my dataframe from a long format into a wide format.
With the current dataframe, this is not possible, because the variable 'Level' is a variable to which multiple answers could be given. When formatting it from long to wide, with the current construction of the dataframe it would not be possible to have one row represent one respondent. So I figured, if I would change the names of the 'Level' variable in the current dataframe to represent unique variables (such as 'Level1', 'Level2','Level3'), each column in my new wide dataframe would represent a binary response to that answer category (0: was not in Level 1, 1: was in level 1).
Like I said, I tried to do this with an if-then statement, but it gives me back an error. I am fairly new to R and I can't seem to find out what I'm doing wrong here. Anyone can give me some feedback?
Here's my script
#current dataframe
resp <- c(1:3,3,3,4,5,6,6)
name <- c("Name","Age","Level","Level","Level","Age","Name","Level","Level")
var <- c("Louis",19,1,2,3,23,"Sander",1,2)
c_df <- data.frame(resp,name,var); c_df
#step 1 towards desired dataframe
resp <- c(1:3,3,3,4,5,6,6)
name2 <- c("Name","Age","Level1","Level2","Level3","Age","Name","Level1","Level2")
var <- c("Louis",19,1,2,3,23,"Sander",1,2)
d_df <- data.frame(resp,name2,var); d_df
#attempt 1: if-then statement
if(c_df[c_df$name=="Level" & c_df$var==1]){
c_df[c_df$name=="Level"] <- "Level1"
}
Error in if (c_df[c_df$name == "Level" & c_df$var == 1]) { :
argument is of length zero
Here is also the script of how I want the dataframe eventually to look like. I know how to work this out myself, I only present it here for clarification :)
#desired wide dataframe
resp <- c(1,2,3,4,5,6)
name <- c("Louis","NA","NA","NA","Sander","NA")
level1 <- c(0,0,1,0,0,1)
level2 <- c(0,0,1,0,0,1)
level3 <- c(0,0,1,0,0,0)
d_df <- data.frame(resp,name,level1,level2,level3); d_df
Aucun commentaire:
Enregistrer un commentaire