I have an existing data set table. For example, the table is called Table1
V1 V2 V3
1 S301 OR 1575.3078990
2 S301 AND 1006.5031070
3 S301 OR 938.3647756
4 S302 OR 1106.0894270
5 S302 AND 1239.9842820
6 S302 OR 885.3624568
I'd like to reorganise this table into a new one where column V2 is split into 'And' and ' Or' columns, with the values being the mean of all the 'And' for S301 in table 1 V2 in the 'And' column
and mean for all the 'OR' for S301 in table 1 V2 in the 'Or column'.
I've been struggling with this for so long so any help would be greatly appreciated! Thank you all so much in advance.
You said you have an existing "data set table". This is not a type in R. I'll assume you meant data.table.
library(data.table)
theDT <- data.table(matrix(c(rep("S301", 3), rep("S302", 3),
c("OR", "AND", "OR", "OR", "AND", "OR",
1575.3, 1006.5, 938.4, 1106.1, 1240, 885.4)),
ncol = 3))
theDT$V3 <- as.numeric(theDT$V3)
> theDT
V1 V2 V3
1: S301 OR 1575.3
2: S301 AND 1006.5
3: S301 OR 938.4
4: S302 OR 1106.1
5: S302 AND 1240.0
6: S302 OR 885.4
then your answer is
> theDT[, mean(V3), by = c("V1","V2")]
V1 V2 V1
1: S301 OR 1256.85
2: S301 AND 1006.50
3: S302 OR 995.75
4: S302 AND 1240.00
To get the AND and OR columns separated, you could do this.
dat.1 <- aggregate(V3~V2+V1,data=dat, mean)
dat.2 <- reshape(m, direction='wide', idvar='V1', timevar='V2')
names(dat.2) <- c('ID', 'AND', 'OR')
dat.1 looks like this
V2 V1 V3
1 AND S301 1006.5031
2 OR S301 1256.8363
3 AND S302 1239.9843
4 OR S302 995.7259
dat.2 will end up looking like this:
ID AND OR
1 S301 1006.503 1256.8363
3 S302 1239.984 995.7259
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.