【发布时间】:2017-07-04 01:12:11
【问题描述】:
我是 R 新手,正在尝试完成以下提示:
编写一个函数,该函数采用数据文件目录和完整案例的阈值,并计算完全观察到的案例数量(所有变量)大于阈值的监视器位置的硫酸盐和硝酸盐之间的相关性。该函数应返回满足阈值要求的监视器的相关向量。如果没有监视器满足阈值要求,则该函数应返回长度为 0 的数字向量。此函数的原型如下:
corr <- function(directory, threshold = 0) {
## 'directory' is a character vector of length 1 indicating the location of
## the CSV files
## 'threshold' is a numeric vector of length 1 indicating the number of
## completely observed observations (on all variables) required to compute
## the correlation between nitrate and sulfate; the default is 0
## Return a numeric vector of correlations
spectdata<- list.files(pattern= ".csv") #creates vector with list of filenames
corr<-function(directory,threshold =0, id = 1:332){
info<-list()
for(i in id){
info<-read.csv(directory[i], header=TRUE)
NOBS<-sum(complete.cases(info))
if (NOBS>threshold){
return(cor(info$nitrate,info$sulfate,use="complete.obs"))
}
}
corr<-sapply(spectdata,corr)
corr<-unlist(corr[!sapply(corr,is.null)])
return(corr)
}
cr<-corr(spectdata,threshold =150)
head(cr)
看起来程序可以运行,但只返回 5 元素向量上的第一个元素:
> cr<-corr(spectdata,threshold =150)
> head(cr)
[1] -0.01895754
应该是什么:
cr <- corr("specdata", 150)
head(cr)
## [1] -0.01895754 -0.14051254 -0.04389737 -0.06815956 -0.12350667 -0.07588814
有人有什么想法吗?我对 R 很陌生,很困惑。例如,如果我尝试将向量定义为更长,我会得到相同的答案(0.01895754 NA NA NA NA)。
【问题讨论】:
-
这可能有很多骗子。请查看here
-
这里至少有四个活动的部分。为了获得更好的响应,请隔离不同的部分并确定出现问题的部分。另见stackoverflow.com/help/mcve
-
你不应该在这里要求评分作业的答案...
-
我有正确的答案,但我无法让向量的其余部分通过 - 应该对代码进行 1-2 次编辑。相信大家可以看到,大部分的工作已经完成了~
-
请发布一些输入数据以获得可重复的示例。 .csv 文件是什么样的?
标签: r