使用lapply和seq_along进行矩阵索引

时间:2015-10-26 21:32:06

标签: r lapply

lapply无效。我得到了以下功能:

testing <- function(x){
     x <- lapply(seq_along(x), function(i) x[[i]][,2] <- c(88,88,88))
     return(x)
}

和测试矩阵列表:

xl <- list(matrix(1:9,3,3),matrix(2:10,3,3))

输出是:

[[1]]
[1] 88 88 88

[[2]]
[1] 88 88 88

为什么会这样?我希望第二列用88替换为88,而不是用88s的向量替换的矩阵。我必须在这里遗漏一些东西。

1 个答案:

答案 0 :(得分:2)

你需要

list

或者我们遍历 lapply(list, function(x) {x[,2] <- 88; x}) ,将第二列更改为88并返回列表元素。

for

或者@Frank提到,我们可以使用list循环并将每个for (j in seq_along(list)) list[[j]][, 2] <- 88 元素的第二列指定为88.

package mysql;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCExample {

  public static void main(String[] argv) {

    System.out.println("-------- MySQL JDBC Connection Testing ------------");

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your MySQL JDBC Driver?");
        e.printStackTrace();
        return;
    }

    System.out.println("MySQL JDBC Driver Registered!");
    Connection connection = null;

    try {
        connection = DriverManager
        .getConnection("jdbc:mysql://192.99.148.171:3306/aldorps_aldorpva_donation","aldorps_donation", "stan1234");

    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;
    }

    if (connection != null) {
        System.out.println("You made it, take control your database now!");
    } else {
        System.out.println("Failed to make connection!");
    }
  }
}