A tidyverse-ish solution would be
library(dplyr)
library(tidyr)
library(tibble)
# max cols to split values into
seps<-max(stringr::str_count(unlist(d1),"[/|]"))+1
d1 %>% pivot_longer(S1:S5, names_to="S") %>%
mutate(value=na_if(value,"w")) %>% separate(value,"[/|]",
into=LETTERS[1:seps], fill="right") %>% pivot_longer(-S, names_to=NULL,
values_to="rownames") %>% filter(!is.na(rownames)) %>%
mutate(index=1L)%>%pivot_wider(names_from=S, values_from=index) %>%
mutate_all(replace_na,0L) %>% column_to_rownames(var = "rownames")
Best, Eik
Am 26.05.2021 um 23:16 schrieb Adrian Johnson:
Hello,
I am trying to convert a df (given below as d1) into df2 (given below as
res).
I tried using loops for each row. I cannot get it right. Moreover the df
is 250000 x 500 in dimension and I cannot get it to work.
Could anyone help me here please.
Thanks.
Adrian.
d1 <-
structure(list(S1 = c("a1|a2", "b1|b3", "w"), S2 = c("w", "b1",
"c2"), S3 = c("a2", "b3|b4|b1", "c1|c4"), S4 = c("w", "b4", "c4"
), S5 = c("a2/a3", "w", "w")), class = "data.frame", row.names = c("A",
"B", "C"))
res <-
structure(list(S1 = c(1L, 1L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L),
S2 = c(0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L), S3 = c(0L,
1L, 0L, 1L, 0L, 1L, 1L, 1L, 0L, 1L), S4 = c(0L, 0L, 0L, 0L,
0L, 0L, 1L, 0L, 0L, 1L), S5 = c(0L, 1L, 1L, 0L, 0L, 0L, 0L,
0L, 0L, 0L)), class = "data.frame", row.names = c("a1", "a2",
"a3", "b1", "b2", "b3", "b4", "c1", "c2", "c4"))
[[alternative HTML version deleted]]
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
--
_____________________________________________________________________
Universitätsklinikum Hamburg-Eppendorf; Körperschaft des öffentlichen Rechts;
Gerichtsstand: Hamburg | www.uke.de
Vorstandsmitglieder: Prof. Dr. Burkhard Göke (Vorsitzender), Joachim Prölß,
Prof. Dr. Blanche Schwappach-Pignataro, Marya Verdel
_____________________________________________________________________
SAVE PAPER - THINK BEFORE PRINTING
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.