I have a dataframe containing "ID" columns.
I want to split the columns named "ID1", "ID2" etc into multiple columns (image attached) such that the characters before and after "/" symbol are in separate columns for each "ID1", "ID2", etc. and the resulting columns are a part of the data frame in a sequence.
The image shows a data frame with the name "df"
I have tried usingwithin(df, ID1 <- do.call("rbind", strsplit(df$ID1, "/", fixed= TRUE)))
However, this results in the column "ID1" being changed to matrix "ID1" within the dataframe.
And if I use the codewithin(df, ID1 <- as.data.frame(do.call("rbind", strsplit(df$ID1, "/", fixed= TRUE))))
then the new columns created overwrite the columns named "Time1", "Conc1", "Blank1", etc.
Further, is it possible to use a loop to convert all such columns "ID1", "ID2", etc in one single go?
tidyr::separate
is meant for these scenario only. Do this
dat <- data.frame(
stringsAsFactors = FALSE,
Date = c("01-01-2020", "02-01-2020", "03-01-2020", "04-01-2020"),
ID1 = c("HL/PS/IITD/QF/227",
"HL/PS/IITD/QF/228","HL/PS/IITD/QF/229","HL/PS/IITD/QF/230"),
Time1 = c(3.252661544, 4.58741088, 6.592053573, 2.776812359),
Conc1 = c(325.2661544, 458.741088, 659.2053573, 277.6812359),
ID2 = c("HL/PS/IITD/TF/500",
"HL/PS/IITD/TF/501","HL/PS/IITD/TF/502","HL/PS/IITD/TF/503"),
Time2 = c(3.149086291, 9.202242653, 7.463162859, 7.944689942),
Conc2 = c(314.9086291, 920.2242653, 746.3162859, 794.4689942)
)
library(tidyverse)
dat %>% separate(ID1, into = paste0('ID1_', 1:5), sep = '\\/') %>%
separate(ID2, into = paste0('ID2_', 1:5), sep = '\\/')
#> Date ID1_1 ID1_2 ID1_3 ID1_4 ID1_5 Time1 Conc1 ID2_1 ID2_2 ID2_3
#> 1 01-01-2020 HL PS IITD QF 227 3.252662 325.2662 HL PS IITD
#> 2 02-01-2020 HL PS IITD QF 228 4.587411 458.7411 HL PS IITD
#> 3 03-01-2020 HL PS IITD QF 229 6.592054 659.2054 HL PS IITD
#> 4 04-01-2020 HL PS IITD QF 230 2.776812 277.6812 HL PS IITD
#> ID2_4 ID2_5 Time2 Conc2
#> 1 TF 500 3.149086 314.9086
#> 2 TF 501 9.202243 920.2243
#> 3 TF 502 7.463163 746.3163
#> 4 TF 503 7.944690 794.4690
Created on 2021-06-13 by the reprex package (v2.0.0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.