使用 sapply 时如何使用函数的参数? [英] How do I use arguments of a function when using sapply?
问题描述
我有一个数据集,它是我使用 gdata
包中的 cbindX
函数通过列绑定创建的.此功能允许我绑定具有不同行数的列.因此,当特定列中没有值时,会引入 NA
.现在,我想计算每列的标准偏差.我尝试使用
I have a dataset which I created by column binding using the cbindX
function from the gdata
package. This function allows me to bind columns with different numbers of rows. So, NA
's are introduced when there are no values in a particular column. Now, I want to calculate the standard deviation for each column. I tried using
sapply(dataset,sd)
这将返回所有行都带有值的列的标准偏差,以及行数较少的列的 NA
的标准偏差.我尝试将 na.rm
参数与 sd
函数一起使用:
This returns the standard deviation for the column having all rows with values and NA
for the columns having fewer rows. I tried using the na.rm
argument with the sd
function:
sapply(dataset,sd(na.rm=T))
并收到错误信息
Error in is.data.frame(x) : argument "x" is missing, with no default
例如:
firstcol <- matrix(c(1:150),ncol=1)
secondcol <- matrix(c(1:300),ncol=1)
thirdcol <- matrix(c(1:450),ncol=1)
fourthcol <- matrix(c(1:600),ncol=1)
fifthcol <- matrix(c(1:30),ncol=1)
sixthcol <- matrix(c(1:30),ncol=1)
seventhcol <- matrix(c(1:30),ncol=1)
library(gdata)
allcolscomb <- data.frame(cbindX (firstcol,secondcol,thirdcol,fourthcol,fifthcol,sixthcol,seventhcol))
names(allcolscomb) <- c("1stcol","2ndcol","3rdcol","4thcol","5thcol","6thcol","7thcol")
sapply(allcolscomb,sd)
sapply(allcolscomb,sd(na.rm=T))
如何使用 sapply
函数计算标准偏差?
How can I compute standard deviation using the sapply
function?
推荐答案
您应该阅读 ?sapply
手册.下面是带有一些额外参数的 sapply 示例:
You should read ?sapply
manual. Below example of sapply with some extra arguments:
sapply(allcolscomb, sd, na.rm=TRUE)
sapply(allcolscomb, function(x) sd(x, na.rm=TRUE))
这篇关于使用 sapply 时如何使用函数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!