简体   繁体   English

从 R 中的现有表创建新表

[英]Creating new table from existing table in R

I have an existing data set table.我有一个现有的数据集表。 For example, the table is called Table1例如,该表称为 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我想将此表重组为一个新表,其中 V2 列被拆分为“And”和“Or”列,其中的值是“And”中表 1 V2 中 S301 的所有“And”的平均值柱子
and mean for all the 'OR' for S301 in table 1 V2 in the 'Or column'.以及表 1 V2 中“或”列中 S301 的所有“或”的平均值。

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.这不是 R 中的类型。我假设您指的是 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.要分离 AND 和 OR 列,您可以这样做。

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 dat.1 看起来像这样

   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: dat.2 最终将如下所示:

    ID      AND        OR
1 S301 1006.503 1256.8363
3 S302 1239.984  995.7259

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM