dataframe - r reshape data using row with NA to identify new column -
i have dataset in r looks this:
df <- data.frame(name=c("a","b","c","d","b","e","f"), x=c(na,1,2,3,na,4,5))
i reshape into:
rdf <- data.frame(name=c("b","c","d","e","f"), x=c(1,2,3,4,5), head=c("a","a","a","b","b"))
where first row na
identifies new column, , takes "row value" until next row na
, , changes "row value".
i have tried both spread
, melt
, not give me want.
library(tidyr) df %>% spread(name,x) library(reshape2) melt(df, id=c('name'))
any suggestions?
here's possible data.table
/zoo
packages combination solution
library(data.table) ; library(zoo) setdt(df)[is.na(x), head := name] na.omit(df[, head := na.locf(head)], "x") # name x head # 1: b 1 # 2: c 2 # 3: d 3 # 4: e 4 b # 5: f 5 b
or suggested @arun, using data.table
na.omit(setdt(df)[, head := name[is.na(x)], by=cumsum(is.na(x))])
Comments
Post a Comment