查找平均值

问题描述:

我试图用n列(在这种情况下是3)创建一个数据帧(df1)。列1应该是来自数据帧df0的随机列。第2列应该是同一个随机列加上df0中的另外四个随机列的平均值。第3列应该是前五个加上另外五个随机列的平均值。查找平均值

+0

我觉得这是更好地问3个问题,因为你有很多文字。还发布预期产出。 – 2016-02-28 10:20:35

+0

请添加'set.seed'以使其具有可重现性。 –

+1

Eitherway,在使用数字列时,最好将其保留为矩阵(以便考虑速度)。你可以用'sapply(c(1,5,10),function(x)rowSums(df0 [,random [1:x],drop = FALSE]))'来实现你的目标。你可以将'c(1,5,10)'调整为你喜欢的任何顺序。 –

我试着一一解答你的问题。让我们从第一

total <- 15 # Total number of columns in df0 
sample <- 10 # Total number of columns I'm extracting from df0 
values <- 4 # Number of rows 
random <- sample(total,sample,replace=FALSE) 
df0 <- data.frame(matrix(data = rexp(values*total, rate = total), nrow = values, ncol = total)) 

#At first I select 10 random columns from df0 
df1 <- df0[, sample(ncol(df0), sample)] 


#I would create an empty data frame 

df2 <- data.frame(matrix(, nrow =values , ncol = 3)) 


#then assign the first column of df1 to the output , 
df2$X1 <- df1[,1] 

#then you get the average of five first random selected to second column of df2 
df2$X2 <- rowMeans(subset(df1[1:5])) 

#finally the average of 10 columns to the third column of df2 
df2$X3 <- rowMeans(subset(df1[1:10])) 


> df2 
#   X1   X2   X3 
#1 0.18816542 0.12617238 0.08728368 
#2 0.09855574 0.07592763 0.06069351 
#3 0.12022571 0.06045562 0.07964574 
#4 0.00260806 0.06172300 0.06225859 

开始为了消除所有不需要的列,我个人使用类似下面 ,但我相信会有另一种方式来做到这一点

# for example you only want to keep column 3 and 5 then 
col_list = c("X3", "X5") 
dfm = df0[,col_list] 
+0

关于第一个问题:似乎在df1 $ X1中选择了一个随机列,但在df1 $ X2中显示了df1的前5列的平均值,而不是df1 $ X1中显示的列的平均值加上另外四个随机列。这确实是这种情况,还是我读错了?需要说明的是:平均5列的列需要包含第一个选择的列(在$ X1中),平均值为10列的列需要包含前五个列和其他五个随机列。 – Joseph

+1

@约瑟夫说实话你的问题有点混乱。所以,让我们澄清你的问题。 1-您创建一个df0,第2步,您要从df0中选择一个随机列并将其放入df1中。第3步,你需要取5个第一列的平均值并放在df1的第2列中,最后你想得到df0的前10列的平均值并将其放入df1中。这是你想要的吗? – 2016-02-28 11:09:13

+0

让我说得有所不同。 1)我创建df0。 2)我从df0中选择10个随机列。 3)第一个随机列进入df1 $ X1。 4)前5个随机列的平均值为df1 $ X2(这5个当然包括步骤3中的第一个随机列;因此包括4个新列)。 5)所有10个随机列的平均值为df1 $ X3。这是否澄清事情? – Joseph