使用sapply或lapply应用lm()

问题描述 投票:0回答:1

所以我试图对sapply使用lm()。

#example data and labels
data <- matrix(data = runif(1000), nrow = 100, ncol = 10))
markers <- sample(0:1, replace = T, size = 100)

# try to get linear model stuff
Lin <- sapply(data, function(x) lm(unlist(markers) ~ unlist(x))$coefficients)

我的问题是,这给了我1000个方程的系数,而不是10个方程

r lapply sapply
1个回答
1
投票

您需要为sapply提供数据帧,而不是矩阵。

#example data and labels
data <- data.frame(matrix(data = runif(1000), nrow = 100, ncol = 10))
markers <- sample(0:1, replace = T, size = 100)

# try to get linear model stuff
sapply(data, function(x) coef(lm(markers ~ x)))    
sapply(data, function(x) coef(lm(markers ~ x))[-1]) # Omit intercepts
        X1.x         X2.x         X3.x         X4.x         X5.x 
 0.017043626  0.518378546 -0.011110972 -0.145848478  0.335232991 
        X6.x         X7.x         X8.x         X9.x        X10.x 
 0.015122184  0.001985933  0.191279594 -0.077689961 -0.107411203

您的原始矩阵失败:

data <- matrix(data = runif(1000), nrow = 100, ncol = 10)
sapply(data, function(x) coef(lm(markers ~ x)))    
# Error: variable lengths differ (found for 'x')

因为调用sapplylapply将在执行功能之前使用as.list将其第一个参数X转换为列表。但是as.list应用于矩阵会导致列表的长度等于矩阵中的条目数,在您的情况下为1,000。 as.list应用于数据框时,将产生一个列表,该列表的长度等于数据框的列数(在您的情况下为10),并且元素包含每一列中的值。


> lapply
function (X, FUN, ...) 
{
    FUN <- match.fun(FUN)
    if (!is.vector(X) || is.object(X)) 
        X <- as.list(X)
    .Internal(lapply(X, FUN))
}
<bytecode: 0x000002397f5ce508>
<environment: namespace:base>
© www.soinside.com 2019 - 2024. All rights reserved.