I'm beginner in R coding. I need a hand to find an elegant way to do this:
I've got the following dataframe :
> df = data.frame(pattern=c('a,b,c','b','c,b','c'), nb=c(150,100,30,10))
> df
pattern nb
1 a,b,c 150
2 b 100
3 c,b 30
4 c 10
According to the presence of string, I want a dataframe like that :
pattern nb a b c
1 a,b,c 150 150 150 150
2 b 100 0 100 0
3 c,b 30 0 30 30
4 c 10 0 0 10
I find this solution :
df$a <- ifelse(grepl("a" , df$pattern), df$nb, 0)
df$b <- ifelse(grepl("b" , df$pattern), df$nb, 0)
df$c <- ifelse(grepl("c" , df$pattern), df$nb, 0)
But in my real case, I got a lot of different patterns. I'm sure there is a way with a loop or function. Of course, I'm not asking for a ready-made solution. I'm just asking for an idea of how to do it. Many thanks in advance.
Greetings from France
Arnaud
Aucun commentaire:
Enregistrer un commentaire