I have a dataframe with multiple columns like this:
df <- data.frame(
Level = c(
'Midwest',
'Wisconsin: Good',
'Wisconsin: Neutral',
'Wisconsin: Bad',
NA,
'Minnesota: Good',
'Minnesota: Neutral',
'Minnesota: Bad',
NA,
'New England',
'New Hampshire: Good',
'New Hampshire: Neutral',
'New Hampshire: Bad',
NA,
'Vermont: Good',
'Vermont: Neutral',
'Vermont: Bad'
),
TotalPct = c(
NA,
'75%',
'71%',
'65%',
NA,
'82%',
'76%',
'53%',
NA,
NA,
'68%',
'98%',
'45%',
NA,
'79%',
'93%',
'48%'
)
)
I'm interested in doing two things to this dataframe:
- Grab the first instance of the
Goodlevel for each state and place it in a new row about theGoodlevel, and... - Remove the state names from each level so it just shows
Good,Neutral, andBadbelow each state name.
The result would look like this:
df_desired <- data.frame(
Level = c(
'Midwest',
'Wisconsin',
'Good',
'Neutral',
'Bad',
NA,
'Minnesota',
'Good',
'Neutral',
'Bad',
NA,
'New England',
'New Hampshire',
'Good',
'Neutral',
'Bad',
NA,
'Vermont',
'Good',
'Neutral',
'Bad'
),
TotalPct = c(
NA,
NA,
'75%',
'71%',
'65%',
NA,
NA,
'82%',
'76%',
'53%',
NA,
NA,
NA,
'68%',
'98%',
'45%',
NA,
NA,
'79%',
'93%',
'48%'
)
)
What's the best way to go about achieving this using R, ideally using dplyr if possible?