Clé*_*t F 5 r correlation dataframe
我目前正在尝试创建一个R函数来计算指定列与数据帧的所有数字列的corr.test相关性.这是我的代码:
#function returning only numeric columns
only_num <- function(dataframe)
{
nums <- sapply(dataframe, is.numeric)
dataframe[ , nums]
}
#function returning a one-variable function computing the cor.test correlation of the variable
#with the specified column
function_generator <- function(column)
{
function(x)
{
cor.test(x, column, na.action = na.omit)
}
}
data_analysis <- function(dataframe, column)
{
DF <- only_num(dataframe)
fonction_corr <- function_generator(column)
sapply(DF, fonction_corr)
}
data_analysis(40, 6, m, DF$Morphine)
Run Code Online (Sandbox Code Playgroud)
当我在最后一行调用"data_analysis"时,我收到以下错误:
"cor.test.default(x,column,na.action = na.omit)中的错误:没有足够的有限观察"
这意味着什么?我应该改变什么?我有点卡住......
谢谢.
克莱门特
Clé*_*t F 10
"没有足够的有限obervations"是cor.test在某些情况下返回的错误.如果你看一下cor.test.default源代码,你会看到:
OK <- complete.cases(x, y)
x <- x[OK]
y <- y[OK]
n <- length(x)
Run Code Online (Sandbox Code Playgroud)
cor.test从你的矢量中移除NA值[...]
if (method = "pearson") {
if (n < 3L)
stop("not enough finite obervations")
Run Code Online (Sandbox Code Playgroud)
[...]
else {
if (n<2)
stop("not enough finite obervations")
Run Code Online (Sandbox Code Playgroud)
如果向量不包含足够的非NA值(小于3),则该函数将返回错误.
在使用cor.test之前,使数据框中的所有列都包含足够的非NA值.
我希望这会有用.
我看不到“m”或“DF$Morphine”是什么,因此我创建了一个包含数字和非数字列的数据框。
# generate some data
set.seed(321)
mydf <- data.frame(A = rnorm(100),
B = rexp(100, 1),
C = runif(100),
D = sample(letters, size=100, replace=TRUE))
Run Code Online (Sandbox Code Playgroud)
我保留了您编写的函数,但以不同的方式调用了 data_analysis 。数据框应作为第一个参数,数值向量应作为第二个参数
data_analysis(dataframe=mydf, column=mydf$C)
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到数据框中每一列的 cor.test 输出。
A B
statistic -0.4153108 -0.4669693
parameter 98 98
p.value 0.6788223 0.6415584
estimate -0.04191585 -0.04711863
null.value 0 0
alternative "two.sided" "two.sided"
method "Pearson's product-moment correlation" "Pearson's product-moment correlation"
data.name "x and column" "x and column"
conf.int Numeric,2 Numeric,2
C
statistic Inf
parameter 98
p.value 0
estimate 1
null.value 0
alternative "two.sided"
method "Pearson's product-moment correlation"
data.name "x and column"
conf.int Numeric,2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11200 次 |
| 最近记录: |