Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 按列将数据帧拆分为两组_R - Fatal编程技术网

R 按列将数据帧拆分为两组

R 按列将数据帧拆分为两组,r,R,我试图根据每列的总和将一个数据帧中的列分隔为两个数据帧 以下是我尝试过的: sum_each_col <- apply(originalDF,2,sum) ave_sum <- mean(sum_each_col) col_k1 <- data.frame() col_k2 <- data.frame() apply(originalDF,2,function(x){ if(sum(x) <=ave_sum){ cbind(col_k1,as

我试图根据每列的总和将一个数据帧中的列分隔为两个数据帧

以下是我尝试过的:

 sum_each_col <- apply(originalDF,2,sum)
 ave_sum <- mean(sum_each_col)

 col_k1 <- data.frame()
 col_k2 <- data.frame()

 apply(originalDF,2,function(x){
 if(sum(x) <=ave_sum){
    cbind(col_k1,as.data.frame(x))
  }
 else {
    cbind(col_k2,as.data.frame(x))
  }
 }
 ) 
预期产出: col_k1:

   col1 col3 
 A  1     1    
 B  1     1     
 C  1     1    
col_k2:

    co2 col4 col5
  A  2    2    2
  B  2    2    2 
  C  2    2    2
你可以试试:

#there is a function colMeans that calculates the mean of each column
index <- colMeans(DF) < mean(colMeans(DF))
以及:


数据:


DF data.frames是无量纲的,因此cbind不会工作,因为行数不同。不需要
索引
#there is a function colMeans that calculates the mean of each column
index <- colMeans(DF) < mean(colMeans(DF))
> DF[index]
  col1 col3
A    1    1
B    1    1
C    1    1
> DF[!index]
  col2 col4 col5
A    2    2    2
B    2    2    2
C    2    2    2
DF <- read.table(header=T, text=' col1 col2 col3 col4 col5
A  1   2    1    2    2
B  1   2    1    2    2  
C  1   2    1    2    2')