Unsplitting a data frame by a variable (different length of factors)
I have a data frame (st1) that I split by a factor. I then performed functions to the split data (i.e. mean) by another factor and hence, I cannot perform unsplit any more because my original data frame is of different length now.
As to walk you through what I did, here is a code:
NT = data.table(st1) NT2=split (NT, NT$bin) NT3 <- data.frame(sapply( NT2 , function(x) x[, list(ang=length(unique(thetadeg)), len=length(T), Vm=mean(V)), by=c("A")]))
head of the st1:
structure(list(A = c(25L, 25L, 25L, 25L, 25L, 25L), T = 56:61, X = c(481.07, 487.04, 490.03, 499, 504.97, 507.96), Y = c(256.97, 256.97, 256.97, 256.97, 256.97, 256.97), V = c(4.482, 5.976, 7.47, 4.482, 5.976, 7.47), thetarad = c(0.164031585831919, 0.169139558949956, 0.171661200692621, 0.179083242584008, 0.183907246800473, 0.186289411097781), thetadeg = c(9.39831757286096, 9.69098287432395, 9.83546230358968, 10.2607139792383, 10.537109061132, 10.6735970214433), bin = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("binA", "binB", "binC", "outbin"), class = "factor")), .Names = c("A", "T", "X", "Y", "V", "thetarad", "thetadeg", "bin"), row.names = c(NA, 6L), class = "data.frame")
I did not put a dput(head) for my NT3 because it will be too long.
I tried unsplit, unlist but am not successful. What I want to do is to have one data frame again with the bin as a factor.
Any help would be great.
edit: What I would like my data frame to have is A, ang, len, Vm, and bin as headers.
It's not altogether clear what your intended output is, but looking at what you have for NT3, this may be more effective:
NT <- data.table(ST1, key="A") NT[, list(ang=length(unique(thetadeg)) , len=length(T) , Vm=mean(V)) , by=list(A, bin) ]
I managed to find what I did wrong, so this now works:
NT <- data.table(st1, key="bin") NT2=NT[, list(ang=length(unique(thetadeg)), len=length(T), Vm=mean(V)), by=c("A", "bin")]
Apparently I could already do in data.table the by statement which was also suggested by @Ricardo Saporta. Thank you for that!