r - apply formula for certain columns using other columns -
i have data frame
dat = data.frame(type = c("a","a","b","b","c","c","d"), nexttype = c("a", "b","b", "c","c","d",na), = c(rep(0,7)), b = rep(0,7), c = rep(0,7) , d = rep(0,7), stringsasfactors = f) dat type nexttype b c d 1 0 0 0 0 2 b 0 0 0 0 3 b b 0 0 0 0 4 b c 0 0 0 0 5 c c 0 0 0 0 6 c d 0 0 0 0 7 d <na> 0 0 0 0
what's best way populate columns a, b , c , d 1 if column name (a, b, c, d etc...) = type = nexttype
so
column 1,0,0,0,0,0,0 column b 0,0,1,0,0,0,0 column c 0,0,0,0,1,0,0 column d 0,0,0,0,0,0,0
note -- has dynamic. have 4 columns above a, b , c , d there can 10, 20 or number of columns.
use dplyr
, tidyr
:
library(dplyr); library(tidyr); dat %>% select(type, nexttype) %>% mutate(key = if_else(type == nexttype & !is.na(type) & !is.na(nexttype), type, "other"), val = 1) %>% spread(key, val, fill = 0) %>% select(-other) # type nexttype b c #1 1 0 0 #2 b 0 0 0 #3 b b 0 1 0 #4 b c 0 0 0 #5 c c 0 0 1 #6 c <na> 0 0 0
data:
dat = data.frame(type = c("a","a","b","b","c","c"), nexttype = c("a", "b","b", "c","c",na), = c(rep(0,6)), b = rep(0,6), c = rep(0,6) , stringsasfactors = f)
Comments
Post a Comment