cbind with loop in R

Deadly 提交于 2021-01-28 19:16:54

问题


I'm new with R and I've an issue So my issue is : I've multiples tables ex: 10 , also different list from kmeans results related to this tables (10). So I want use cbind in order to add each cluster to its table :

Ex:

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

...

I've tryd with this code but a get an error

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

回答1:


Without seeing the data I'll have a guess that this might work:

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

where tables is a list of your tables i.e. list(tables) and kmeans is a list of your kmeans i.e. 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))



回答2:


I guess what you want might be something like below

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



回答3:


thank you all, I'v fixed by the following code:

# 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)
    )
}


来源:https://stackoverflow.com/questions/60321045/cbind-with-loop-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!