1
X  Income Limit Rating Cards Age Education Gender Student Married Ethnicity Balance
1 1  14.891  3606    283     2  34        11   Male      No     Yes Caucasian     333
2 2 106.025  6645    483     3  82        15 Female     Yes     Yes     Asian     903
3 3 104.593  7075    514     4  71        11   Male      No      No     Asian     580
4 4 148.924  9504    681     3  36        11 Female      No      No     Asian     964
5 5  55.882  4897    357     2  68        16   Male      No     Yes Caucasian     331
6 6  80.180  8047    569     4  77        10   Male      No      No Caucasian    1151

Above is head of my data frame. I have a df w/12 columns. These cols are of type "integer", "numeric" or "Factor". I wish to create a subset data frame that contains only the cols of type "integer" or "character".

I tried this code, but it doesn't work. I would prefer an answer that uses data frame, although I attempted matrix.

z <- matrix(data = NA, nrow = 400 , ncol = 8 )
for(i in 2: dim(credit.csv)[2]) {
  if (class(credit.csv[2,i]) == "integer" | "numeric") 
  { 
  z[,i] <- credit.csv[,i]; i = i +1 
  else (skip)
  }
}


> str(credit.csv)
'data.frame':   400 obs. of  12 variables:
 $ X        : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Income   : num  14.9 106 104.6 148.9 55.9 ...
 $ Limit    : int  3606 6645 7075 9504 4897 8047 3388 7114 3300 6819 ...
 $ Rating   : int  283 483 514 681 357 569 259 512 266 491 ...
 $ Cards    : int  2 3 4 3 2 4 2 2 5 3 ...
 $ Age      : int  34 82 71 36 68 77 37 87 66 41 ...
 $ Education: int  11 15 11 11 16 10 12 9 13 19 ...
 $ Gender   : Factor w/ 2 levels " Male","Female": 1 2 1 2 1 1 2 1 2 2 ...
 $ Student  : Factor w/ 2 levels "No","Yes": 1 2 1 1 1 1 1 1 1 2 ...
 $ Married  : Factor w/ 2 levels "No","Yes": 2 2 1 1 2 1 1 1 1 2 ...
 $ Ethnicity: Factor w/ 3 levels "African American",..: 3 2 2 2 3 3 1 2 3 1 ...
 $ Balance  : int  333 903 580 964 331 1151 203 872 279 1350 ...

1 Answers1

0

If you want only integer/numeric columns then exclude character columns

credit.Int =data[,! names(data) %in% c("Gender","Married", "Ethnicity") ]

so this is your numeric data frame

and you can do vice versa for character data frame

Pankaj Sharma
  • 388
  • 7
  • 18
  • You missed `Student` columns, because your approach is not general enough. See the duplicate. –  Oct 30 '15 at 04:07
  • @pascal student column can be added...whats the big deal... – Pankaj Sharma Oct 30 '15 at 04:19
  • You missed the point that your solution is not general enough. How about a data.frame with 50 columns and half with character? You will enter by hand 25 names? –  Oct 30 '15 at 04:22
  • It works for this question and.. thats all person asked... so at this point its enough.. nwy you can always comment... – Pankaj Sharma Oct 30 '15 at 04:26
  • I was trying to point a reasonable direction to improve your answer. –  Oct 30 '15 at 04:28