I have this dataframe in R
library(dplyr)
library(tidyr)
df <- tibble(
ID = 1,
`Zebra fish (one)` = 3,
`Zebra fish (two)` = 4,
`Dog-caut (zero)` = 9,
`Dog-caut (hello there)` = 12
)
and try to make this one, but as you can see the TYPE column always comes up empty, how do i fix it?
# Reshaping the dataframe
long_df <- df %>%
pivot_longer(
cols = -ID,
names_to = "CATEGORY_TYPE",
values_to = "SCORE"
) %>%
separate(CATEGORY_TYPE, into = c("CATEGORY", "TYPE"), sep = " \\(") %>%
mutate(TYPE = sub("\\)", "", TYPE))
The data frame should look like this,
ID, CATEGORY, TYPE, SCORE
1, Zebra fish, one, 3
1, Zebra fish, two, 4
1, Dog-caut, zero, 9
1, Dog-caut, hello there, 12
The string I wish to separate is in this format
ID, 'Zebra fish (one)--Hello; blah'
1, 7
And I am hoping to put it in this format:
ID, CATEGORY, TYPE1, TYPE2, VALUE
1, Zebra fish, one, hello, 7
This may be a good example of when to use
tidyr::separate_wider_delim:And if you want to clean it up with removing periods, add an extra
mutate:In the updated data you provided, you could try: