data.table - create data frame based on unique values of two variables in R -


i create new data frame based on 2 unique values data frame.

id <- c("a", "b", "b", "c") st.name <- c("tx", "tx", "ca", "ca")  type <- c(21, 26, 29, 24) df <- data.frame(id, st.name, type) print(df)  id st.name type        tx   21   b      tx   26   b      ca   29   c      ca   24   

i create new data frame based on unique values of id , st.type. result like:

new_id <- c("atx", "aca", "btx", "bca", "ctx", "cca") new_type <- c(21, na, 26, 29, na, 24) df2 <- data.frame(new_id, new_type) print(df2)  new_id new_type   atx       21   aca       na   btx       26   bca       29   ctx       na   cca       24   

i have used dcast in previous projects, not sure how incorporate function here.

we can complete , unite tidyr

library(tidyr) complete(df, id, st.name) %>%                unite(new_id, id, st.name, sep = '') 

or using base r, can expected output expand.grid, merge , paste

transform(merge(expand.grid(lapply(df[1:2], unique)),              df, all.x=true), id = paste0(id, st.name))[-2] 

or data.table option cj (mentioned @frank in comments)

library(data.table) setdt(df)[cj(id = id, st.name = st.name, unique=true), on=.(id, st.name)] 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -