[R] Fetching a range of columns

David Winsemius dwinsemius at comcast.net
Mon Sep 15 01:20:55 CEST 2008


On Sep 14, 2008, at 5:39 PM, Adam D. I. Kramer wrote:

> Hi Jason,
>
> data[] is a data frame, remember--you need to specify rows AND  
> columns. So,
> data[,c(2,12,17)] is what you should be doing in the first place, and
> data[,842:2411] in the second place.

Actually, the construction df[c(2,12,17)] will return just the 2nd,  
12th and 17th named column vectors.

Try it and see:

  df <- data.frame(a=1:10, b= 10:1, c=LETTERS[1:10])
  df
  df[c(2,3)]
>
> Not sure if the help you needed was using the comma, or the :  
> syntax, or if
> you're trying to read only certain columns during the read.csv process
> (which I don't think that's possible).

? colClasses  # with the vector element of NULL for each unwanted  
column.

I am not the person to be advising how to do this properly, as all of  
my efforts to use this facility to date have failed and I have  
resorted to reading in lines  with as.is=TRUE and then post- 
processing. But the facility does exist.

Maybe someone could give me a clue how one might construct a vector to  
send to colClasses inside read.table?

 > mt <- matrix(1:200,nrow=4)
 > write.table(file=file.choose(), as.data.frame(mt))
 > read.table(file.choose())
   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19  
V20 V21 V22 V23 V24 V25 V26 V27 V28 V29
1  1  5  9 13 17 21 25 29 33  37  41  45  49  53  57  61  65  69  73   
77  81  85  89  93  97 101 105 109 113
2  2  6 10 14 18 22 26 30 34  38  42  46  50  54  58  62  66  70  74   
78  82  86  90  94  98 102 106 110 114
3  3  7 11 15 19 23 27 31 35  39  43  47  51  55  59  63  67  71  75   
79  83  87  91  95  99 103 107 111 115
4  4  8 12 16 20 24 28 32 36  40  44  48  52  56  60  64  68  72  76   
80  84  88  92  96 100 104 108 112 116
   V30 V31 V32 V33 V34 V35 V36 V37 V38 V39 V40 V41 V42 V43 V44 V45 V46  
V47 V48 V49 V50
1 117 121 125 129 133 137 141 145 149 153 157 161 165 169 173 177 181  
185 189 193 197
2 118 122 126 130 134 138 142 146 150 154 158 162 166 170 174 178 182  
186 190 194 198
3 119 123 127 131 135 139 143 147 151 155 159 163 167 171 175 179 183  
187 191 195 199
4 120 124 128 132 136 140 144 148 152 156 160 164 168 172 176 180 184  
188 192 196 200

Not working efforts:
tstdta <- read.table(file.choose(), colClasses = c(c(paste(rep("NULL", 
49),sep=","),"numeric"),header=TRUE)
tstdta <- read.table(file.choose(), colClasses = paste(rep("NULL", 
49),"numeric",sep=","),header=TRUE)

-- 
David Winsemius



More information about the R-help mailing list