【问题标题】:Reading Every Other Column in CSV into alternating matrix in R将CSV中的每隔一列读入R中的交替矩阵
【发布时间】:2013-12-06 17:35:52
【问题描述】:

我需要读取一个没有标题且列数和行数未知的 CSV 文件。但是,每隔一列都属于一个矩阵,而下一列需要在不同的矩阵中。示例

CSV 输入:

1,2,3,4
1,2,3,4
1,2,3,4
1,2,3,4

期望的结果相当于:

matrix1 <- (c( 1, 3,
               1, 3,
               1, 3,
               1, 3), NumberOfRows, NumberOfColumns, byrow=T);

matrix2 <- (c( 2, 4,
               2, 4,
               2, 4,
               2, 4), NumberOfRows, NumberOfColumns, byrow=T);

我已经尝试过类似的方法(但这似乎过于复杂并且无论如何都不起作用)。在 R 中没有一种简单的方法可以做到这一点吗?

mydata<- read.csv("~/Desktop/file.csv", header=FALSE, nrows=4000);
columnCount<-ncol(mydata);
rowCount<-nrow(mydata);
evenColumns <- matrix(); oddColumns <-matrix();

for (i in 1:columnCount) {
  if (i %% 2) {
    for (l in 1:rowCount){
      col <- 1;
      evenColumns[col, l] <-mydata[i,l];  
      col<-col+1;
    }
  }
  else {
    for (l in 1:rowCount){
      col <-1;
      oddColumns[col, l] <-mydata[i,l];
      col<-col+1;
    }
  }
}

这应该如何在 R 中正确完成?

【问题讨论】:

    标签: r csv matrix


    【解决方案1】:

    您可以通过seq获取列号:

    full = read.csv("mat.csv", header=FALSE)
    
    odds = as.matrix(full[, seq(1, ncol(full), by=2)])
    evens = as.matrix(full[, seq(2, ncol(full), by=2)])
    

    输出:

    > odds
         V1 V3
    [1,]  1  3
    [2,]  1  3
    [3,]  1  3
    [4,]  1  3
    > evens
         V2 V4
    [1,]  2  4
    [2,]  2  4
    [3,]  2  4
    [4,]  2  4
    

    【讨论】:

      【解决方案2】:

      here讨论的问题类似

      mat.even <- mydata[,which(1:ncol(mydata) %% 2 == 0)]
      mat.odd <- mydata[,which(1:ncol(mydata) %% 2 == 1)]
      

      【讨论】:

      • 甚至dat[seq_along(dat) %% 2 == 1]
      【解决方案3】:

      从第一个开始每隔一个:

      > cdat[ , c(TRUE,FALSE)]
        V1 V3
      1  1  3
      2  1  3
      3  1  3
      4  1  3
      

      从第二个开始每隔一个:

      > cdat[ , !c(TRUE,FALSE)]
        V2 V4
      1  2  4
      2  2  4
      3  2  4
      4  2  4
      

      【讨论】:

        猜你喜欢
        • 2018-07-04
        • 1970-01-01
        • 2011-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多