【发布时间】:2018-06-20 14:26:37
【问题描述】:
我正在尝试创建一个函数,该函数使用称为“主”的数据框中的各个数据列之间的相关性填充空数据框“虚拟”。
这是我的功能:
master <- read.table("~/Desktop/Heatmap_Project/master.txt", header = T, sep = "\t", stringsAsFactors = F)
vector_a <- names(master)[2:4]
vector_b <- names(master)[11:18]
# Such that, you compare every column in vector_a with every column in vector_b
heatmap_prep <- function(dataframe, vector_a,vector_b){
dummy <- as.data.frame(matrix(0, ncol=length(vector_a), nrow=length(vector_b)))
for (i in 1:length(vector_a)){
first_value <- dataframe[[ vector_a[i] ]]
# print(first_value)
for(j in 1:length(vector_b)){
second_value <- dataframe[[ vector_b[j] ]]
# print(second_value)
result <- cor(first_value, second_value)
dummy [i,j] <- result
}
}
return(as.matrix(dummy))
}
heatmap_data_matrix1 <- heatmap_prep(master,vector_a, vector_b)
它在“返回”之前一直有效,但是当我运行函数“heatmap_prep”时,它会返回一堆 NA。我希望它用所有相关性填充整个矩阵。
我哪里做错了?
非常感谢。
【问题讨论】:
-
请不要在您的示例中使用
read.table。对其他人来说毫无用处。而是提供一些可重现的实际虚拟数据
标签: r function for-loop matrix heatmap