与R中的循环绑定

问题描述 投票:1回答:3

我是R的新手,但遇到了问题所以我的问题是:我有倍数表ex:10,与与该表有关的kmeans结果列表也不同(10)。因此,我想使用cbind以便将每个群集添加到其表中:

Ex:

NEW_table1<- cbind(table1,kmeans_table1$cluster)
NEW_table2<- cbind(table2,kmeans_table2$cluster)

...

我尝试使用此代码,但出现错误

for (i in 1:10)
{ assign(paste0("NEW_table", i)<-cbind(as.name(paste0("filter_table",i)),Class=(i$cluster) )) 
}

> Error in i$cluster : $ operator is invalid for atomic vectors
r loops cbind
3个回答
0
投票

没有看到数据,我猜测这可能有效:

do.call(cbind, mapply(function(x, y) cbind(x, y), tables, kmeans, simplify=F))

其中table是表的列表,即list(tables)而kmeans是您的kmeans的列表,即list(kmeans)

x = 1:10
x2 = list(x, x, x)

y = 10:1
y2 = list(y, y, y)

do.call(cbind, mapply(function(x, y) cbind(x, y), x2, y2, SIMPLIFY = F))

0
投票

我想你想要的可能是下面的东西

list2env(setNames(lapply(paste0("table",1:10), function(v) cbind(get(v),get(paste0("kmeans_",v))$cluster)),
                  paste0("NEW_table",1:10)),
         envir = .GlobalEnv)

0
投票

谢谢大家,我用下面的代码修复了:

# VAR its a list of distinct values from column in large table
VAR<- unique(table$column)

for(i in VAR){
  assign( 

    paste0("New_table", i),cbind(get(paste0("filter_table",i)),Class=get(i)$cluster)
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.