tidyverse - Match associated factors into new columns in R -
using below data, make generalized convert single column factors separate linked columns. here 'letters' column create 2 new columns 'a' , 'b'.
data <- data.frame(letters = c("a", "a", "b", "c"),ints = c(1, 2, 1, 1), reals = c(.01, .22, .01, .02)) letters ints reals 1 0.01 2 0.22 b 1 0.01 b 1 0.02
would return this.
ints b 1 .01 na 2 .22 na 1 na .01 1 na .02
is there way using tidytext example? or perhaps expanding on work:
model.matrix( ints ~ letters + reals, data = data )
there should not c in letters
variable showed in data.frame.
you can using dplyr
, tidyr
if have many letters
data1 <- data %>% dplyr::mutate(id=seq_len(nrow(.))) %>% tidyr::spread(letters, reals) %>% dplyr::arrange(id) > data1 ints id b 1 1 1 0.01 na 2 2 2 0.22 na 3 1 3 na 0.01 4 1 4 na 0.02
or if have 2 letters , b, can using ifelse.
library(dplyr) data1 <- data %>% dplyr::mutate(a = ifelse(letters=="a"&ints%in%c(1,2), reals, na), b = ifelse(letters=="b"&ints==1, reals, na)) > data1 letters ints reals b 1 1 0.01 0.01 na 2 2 0.22 0.22 na 3 b 1 0.01 na 0.01 4 b 1 0.02 na 0.02
Comments
Post a Comment