I have a dataframe like this
ID <- c("ID21","ID22","ID23","ID24")
STR_PL_CAN_EVOLVE_PROCESS <- c("CCP_A,CCP_B","CCQ_A,CCQ_B,CCQ_C","IOT_A,CCP_B","CCQ_B,IOT_B")
Average <- c(7.5,6.5,7.1,6.6)
STR_VD_CAN_MEASURE_PROCESS <- c("Length,Breadth","Breadth,Width","Height,Length,Width","Width,Length")
Passfail <- c("Pass","Pass","Fail","Fail")
df <- data.frame(ID,STR_PL_CAN_EVOLVE_PROCESS,Average,STR_VD_CAN_MEASURE_PROCESS,Passfail,stringsAsFactors=FALSE)
I am trying to separate the values in the columns ending with "process" into several columns using tidyverse and doing it this way.
library(tidyverse)
df1 <- df %>%
separate(STR_PL_CAN_EVOLVE_PROCESS,
paste0("ST_PL_CA_EV_PR","_Path",
seq(1:10)),
sep = ",") %>%
separate(STR_VD_CAN_MEASURE_PROCESS,
paste0("ST_VD_CA_ME_PR","_Path",
seq(1:10)),
sep = ",")
This works but I manually do a lot of things here (input the column names, new column names). Here are some things that I am trying to achieve
- Automatically supply the names of the columns ending with "PROCESS" and separate those columns.
- Extract the first 2 characters in the columns names (separated by underscores) as new column names. For example:
STR_PL_CAN_EVOLVE_PROCESS
becomesST_PL_CA_EV_PR
- Remove columns that are only NA's
My desired output is
ID ST_PL_CA_EV_PR_Path1 ST_PL_CA_EV_PR_Path2 ST_PL_CA_EV_PR_Path3 Average ST_VD_CA_ME_PR_Path1 ST_VD_CA_ME_PR_Path2 ST_VD_CA_ME_PR_Path3 Passfail
ID21 CCP_A CCP_B <NA> 7.5 Length Breadth <NA> Pass
ID22 CCQ_A CCQ_B CCQ_C 6.5 Breadth Width <NA> Pass
ID23 IOT_A CCP_B <NA> 7.1 Height Length Width Fail
ID24 CCQ_B IOT_B <NA> 6.6 Width Length <NA> Fail
My actual dataset has around 35 columns ending with "PROCESS". Can someone point me in the right direction?