How to delete and keep some columns for a txt file in R? -
How to delete and keep some columns for a txt file in R? -
i have file in txt format , delimited tabs, here extract:
id 1 2 4 15 18 20 1_at 100 200 89 189 299 788 2_at 8 78 33 89 90 99 3_xt 300 45 53 234 89 34 4_dx 49 34 88 8 9 15
now have file, in txt format, , separated commas next data:
18,1,4,20
so based on file, read , extract columns first tabulated info can store in file this:
(important: need maintain order of info stored according csv file)
id 18 1 4 20 1_at 299 100 89 788 2_at 90 8 33 99 3_xt 89 300 53 34 4_dx 9 49 88 15
if info want extract rows easier because read row row , comparing txt file (i have done that), stuck column stuff.
i wonder if there way extract straight columns using subindex function?
any help appreciated.
this 1 way of doing want if don't want read whole file , filter. way work if don't know classes of each column before hand. this illustration assumes input file has column names not starting digits not allowed in r. work digits column name well, cautious may fail in other operations.
> txt = 'id 1 2 4 15 18 20 + 1_at 100 200 89 189 299 788 + 2_at 8 78 33 89 90 99 + 3_xt 300 45 53 234 89 34 + 4_dx 49 34 88 8 9 15' > > df <- read.table(textconnection(txt), header=t, nrows=1, check.names=f) > > df id 1 2 4 15 18 20 1 1_at 100 200 89 189 299 788 > > #lets f column filter read other file > f <- c("id", "18", "1", "4", "20") > > f [1] "id" "18" "1" "4" "20" > > #get column classes > cc <- sapply(df, class) > cc id 1 2 4 15 18 20 "factor" "integer" "integer" "integer" "integer" "integer" "integer" > #specify columns don't want read "null" > cc[!names(cc) %in% f] <- "null" > cc id 1 2 4 15 18 20 "factor" "integer" "null" "integer" "null" "integer" "integer" > > #read whole info frame 1 time again > df <- read.table(textconnection(txt), header=t, colclasses=cc, check.names=f) > > #get columns in desired order > df[,f] id 18 1 4 20 1 1_at 299 100 89 788 2 2_at 90 8 33 99 3 3_xt 89 300 53 34 4 4_dx 9 49 88 15
r file calculated-columns
Comments
Post a Comment