简体   繁体   English

从数据框R中提取特定类型的列和特定命名的列

[英]Extracting a specific type columns and specific named columns from a data frame-R

Let I have a data frame where some colums rae factor type and there is column named "index" which is not a column. 让我有一个数据框,其中有一些列系数因子类型,并且有一个名为“索引”的列,它不是列。 I want to extract columns 我想提取列

  • which are factor tyepe and 这是典型的
  • the "index" column. “索引”列。

For example let 例如让

df<-data.frame(a=runif(10),b=as.factor(sample(10)),index=as.numeri(1:10))

So df is: 所以df是:

         a  b index
0.16187501  5     1
0.75214741  8     2
0.08741729  3     3
0.58871514  2     4
0.18464752  9     5
0.98392420  1     6
0.73771960 10     7
0.97141474  6     8
0.15768011  7     9
0.10171931  4    10

Desired output is(let it be a data frame called df1) 所需的输出是(让它是一个称为df1的数据帧)

df1: DF1:

   b index
   5     1
   8     2
   3     3
   2     4
   9     5
   1     6
  10     7
   6     8
   7     9
   4    10

which consist the factor column and the column named "index". 其中包括因子列和名为“索引”的列。

I use such a code 我用这样的代码

  vars<-apply(df,2,function(x) {(is.factor(x)) || (names(x)=="index")})

  df1<-df[,vars]

However, this code does not work. 但是,此代码不起作用。 How can I return df1 using apply types function in R? 如何在R中使用Apply类型函数返回df1? I will be very glad for any help. 我会很高兴为您提供任何帮助。 Thanks a lot. 非常感谢。

You could do: 您可以这样做:

df[ , sapply(df, is.factor) | grepl("index", names(df))]

I think two things went wrong with your method: First, apply converts the data frame to a matrix, which doesn't store values as factors (see here for more on this). 我认为您的方法出错了两点:首先, apply将数据框转换为矩阵,该矩阵不将值存储为因子(有关此内容 ,请参见此处 )。 Also, in a matrix, every value has to be of the same mode (character, numeric, etc.). 同样,在矩阵中,每个值都必须具有相同的模式(字符,数字等)。 In this case, everything gets coerced to character, so there's no factor to find. 在这种情况下,所有内容都被强制转换为字符,因此没有任何因素可寻。

Second, the column name isn't accessible within apply (AFAIK), so names(x) returns NULL and names(x)=="index" returns logical(0) . 其次,在apply (AFAIK)中无法访问列名称,因此names(x)返回NULLnames(x)=="index"返回logical(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM