Skip to content

Extracting columns

1 message · arun

#
HI Silvano,

I was using the sample() to create column names without a given seed.? So, there was a possibility of having the same column names for list elements. ? In your case, there are fixed number of columns and I believe no two columns from all the 22 files have the same column name.? The code will get all those columns that match the 100 column names from another file.

For example:
set.seed(423)

list1<-lapply(1:5,function(x) data.frame(matrix(sample(1:100,50,replace=TRUE),ncol=5)))
colnames(list1[[1]])<-sample(paste0("A",1:10),5,replace=FALSE)
?colnames(list1[[2]])<-sample(paste0("A",11:20),5,replace=FALSE)
?colnames(list1[[3]])<-sample(paste0("A",21:30),5,replace=FALSE)
?colnames(list1[[4]])<-sample(paste0("A",31:40),5,replace=FALSE)
?colnames(list1[[5]])<-sample(paste0("A",41:50),5,replace=FALSE)


coldat<-data.frame(col1=c("A21","A31","A47")) 
? res <- do.call(cbind, lapply(list1, function(x) x[colnames(x) %in%
?coldat[ , 1]]))
?res
#?? A21 A31 A47
#1?? 66? 52? 60
#2?? 78? 89? 32
#3?? 28? 45? 83
#4?? 45? 33? 94
#5??? 6? 35? 41
#6?? 89? 31? 32
#7?? 91? 91? 46
#8?? 30? 73? 12
#9?? 89? 67?? 8
#10? 11?? 8? 97



A.K.




----- Original Message -----
From: Silvano Cesar da Costa <silvano at uel.br>
To: arun <smartpink111 at yahoo.com>
Cc: 
Sent: Thursday, November 8, 2012 3:22 PM
Subject: Re: [R] Extracting columns

Thanks Arun, but the columns need be unique.
+?  data.frame(matrix(sample(1:100, 50, replace=TRUE), ncol=5)))
+?  colnames(x) <- sample(paste0("A", 1:50), 5, replace=FALSE)
+?  return(x)})
needs to be extracted
coldat[ , 1]]))
? ? A9 A35 A35 A7
1? 100? 97? 65 85
2?  92?  4? 11 53
3?  99? 18? 75 73
4?  69? 15? 58 89
5?  65? 80? 72 71
6?  81? 92? 18 23
7?  95? 65? 60? 1
8?  92? 66? 29 88
9?  61? 59?  9 88
10? 45? 54?  7 80
---------------------------------------------
Silvano Cesar da Costa

Universidade Estadual de Londrina
Centro de Ci?ncias Exatas
Departamento de Estat?stica

Fone: (43) 3371-4346
---------------------------------------------