dataframe - Append each data frame iteratively into a larger data frame R + replicate the pivot functionality in Excel -
i did search , linking entries here, here , here.
but don't answer question.
code:
for (i in 1:nrow(files.df)) { final <- parser(as.character(files.df[i,])) final2 <- rbind(final2,final) }
files.df contains on 30 filenames (read directory using list.files) passed custom function parser returns dataframe holding on 100 lines (number varies 1 file next). both final , final2 initialised na outside loop. script runs fine rbind semantic issue - resulting output not expect. resulting dataframe lot smaller files combined.
i has rbind bit.
secondly, looking mimic pivot functionality that's in excel, whereby have 4 columns, first column repeated each row, second column distinct, third column distinct, fourth column distinct. final dataframe should pivoted around first column. idea how can achieve this? had go @ cast , melt no avail.
any thoughts great! if can stick data frame structure.
attaching pictures reference:
for pivot functionality requires transforming dataframe long wide format, aggregating on value
column, can use base r's reshape():
reshapedf <- reshape(df, v.names = c("value"), timevar=c("identifier"), idvar = c("date"), direction = "wide") # rename columns names(reshapedf) <- c('date', 'a', 'b', 'c') # convert nas zeros reshapedf[,c(2:4)] <- data.frame(sapply(reshapedf[,c(2:4)], function(x) ifelse(is.na(x),0,x))) # reset row.names row.names(reshapedf) <- 1:nrow(reshapedf)
alternatively, dedicated package, reshape2 seen below tends less wordy , less post-formatting. hence, prefer transformation route. plus, excel pivot tables other aggregate functions available (sum, mean, length, etc.):
library(reshape2) reshape2df <- dcast(df, date~identifier, sum, value.var="value")
Comments
Post a Comment