我写了一些代码来获取从1到16的聚类结果的row.names。这是有效的,但是你可以看到很多行:
Factor1 <- row.names(subset(res.uc.df, uc.seed17 == 1))
Factor2 <- row.names(subset(res.uc.df, uc.seed17 == 2))
Factor3 <- row.names(subset(res.uc.df, uc.seed17 == 3))
Factor4 <- row.names(subset(res.uc.df, uc.seed17 == 4))
Factor5 <- row.names(subset(res.uc.df, uc.seed17 == 5))
Factor6 <- row.names(subset(res.uc.df, uc.seed17 == 6))
Factor7 <- row.names(subset(res.uc.df, uc.seed17 == 7))
Factor8 <- row.names(subset(res.uc.df, uc.seed17 == 8))
Factor9 <- row.names(subset(res.uc.df, uc.seed17 == 9))
Factor10 <- row.names(subset(res.uc.df, uc.seed17 == 10))
Factor11 <- row.names(subset(res.uc.df, uc.seed17 == 11))
Factor12 <- row.names(subset(res.uc.df, uc.seed17 == 12))
Factor13 <- row.names(subset(res.uc.df, uc.seed17 == 13))
Factor14 <- row.names(subset(res.uc.df, uc.seed17 == 14))
Factor15 <- row.names(subset(res.uc.df, uc.seed17 == 15))
Factor16 <- row.names(subset(res.uc.df, uc.seed17 == 16))
所以,我只是编写我的第一个循环来减少行数并优化代码,但遗憾的是这不起作用。
Factor=NULL
for(i in 1:16) {
Factor[i] <- row.names(subset(res.uc.df, uc.seed17 == i))
}
有人可以指出我犯的错误吗?
答案 0 :(得分:0)
尝试
lst1 <- lapply(1:16, function(i) row.names(subset(res.uc.df, uc.seed17==i)))
或使用您的代码
lst2 <- list()
for(i in 1:16){
lst2[[i]] <- row.names(subset(res.uc.df,uc.seed17==i))
}
identical(lst1, lst2)
#[1] TRUE
如果您想创建16个Factor
个对象
list2env(setNames(lst1, paste0("Factor", seq_along(lst1))), envir=.GlobalEnv)
# <environment: R_GlobalEnv>
Factor1
#[1] "35" "37" "43"
Factor16
#[1] "16" "17" "23" "24" "44" "46" "49"
set.seed(42)
res.uc.df <- data.frame(uc.seed17=sample(1:16,50,replace=TRUE), val=rnorm(50))