I have a column data$Floor
from a dataset imported from CSV that supposedly contains the floor of an apartment. Here is a sample data:
Floor |
---|
Ground out of 2 |
1 out of 3 |
I wish to separate the data to have the floor and the total floors as following:
Floor | Total Floors |
---|---|
Ground | 2 |
1 | 3 |
I have done write(str_replace_all(data$Floor, "out of", " "), data)
with the intention of splitting the columns where the space is, then writing the changes to the dataset data
but I have no idea how to do that.
CodePudding user response:
You can use tidyr::separate
:
tidyr::separate(data, Floor, c('Floor', 'Total Floors'), sep = ' out of ')
#> Floor Total Floors
#> 1 Ground 2
#> 2 1 3
Data used
data <- data.frame(Floor = c("Ground out of 2", "1 out of 3"))
data
#> Floor
#> 1 Ground out of 2
#> 2 1 out of 3
CodePudding user response:
Using strsplit
from base R.
strsplit(data$Floor, ' out of ') |> rbind.data.frame() |> setNames(c('Floor', 'Total Floors'))
# Floor Total Floors
# 1 Ground 1
# 2 2 3