【问题标题】:Create subset data frame keeping only the columns that are type "integer" or "numeric" [duplicate]创建子集数据框,仅保留“整数”或“数字”类型的列[重复]
【发布时间】:2015-10-30 03:25:59
【问题描述】:
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

上面是我的数据框的头部。我有一个 df w/12 列。这些列的类型为“整数”、“数字”或“因子”。我希望创建一个仅包含“整数”或“字符”类型的列的子集数据框。

我试过这段代码,但它不起作用。尽管我尝试了矩阵,但我更喜欢使用数据框的答案。

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 ...

【问题讨论】:

  • 但是你已经知道你没有任何字符列了。

标签: r


【解决方案1】:

如果您只想要整数/数字列,则排除字符列

credit.Int =数据[,!姓名(数据) %in% c("性别","已婚", "种族") ]

这是你的数字数据框

你可以对字符数据框反之亦然

【讨论】:

  • 您错过了Student 列,因为您的方法不够通用。查看副本。
  • @pascal 学生专栏可以添加...有什么大不了的...
  • 您错过了解决方案不够通用的问题。一个有 50 列和一半有字符的 data.frame 怎么样?您将手动输入 25 个名称?
  • 它适用于这个问题,而且..这就是所有人都问过的......所以在这一点上它已经足够了......你可以随时发表评论......
  • 我试图指出一个合理的方向来改进你的答案。
猜你喜欢
  • 2019-09-06
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 2020-03-31
  • 1970-01-01
相关资源
最近更新 更多