从数据框中提取特定类型的列和特定的命名列-R
Extracting a specific type columns and specific named columns from a data frame-R
让我有一个数据框,其中一些列 rae 因子类型,并且有一个名为 "index" 的列,它不是列。我想提取列
- 哪些是因子类型
- "index" 列。
例如让
df<-data.frame(a=runif(10),b=as.factor(sample(10)),index=as.numeri(1:10))
所以 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
期望的输出是(让它成为一个名为 df1 的数据框)
df1:
b index
5 1
8 2
3 3
2 4
9 5
1 6
10 7
6 8
7 9
4 10
其中包含因子列和名为 "index" 的列。
我用的是这样的代码
vars<-apply(df,2,function(x) {(is.factor(x)) || (names(x)=="index")})
df1<-df[,vars]
但是,此代码不起作用。我如何 return df1 在 R 中使用应用类型函数?我会很高兴任何帮助。非常感谢。
你可以这样做:
df[ , sapply(df, is.factor) | grepl("index", names(df))]
我认为您的方法有两个问题:首先,apply
将数据框转换为矩阵,矩阵不将值存储为因子(有关更多信息,请参阅 ) .此外,在矩阵中,每个值都必须具有相同的模式(字符、数字等)。在这种情况下,一切都被强制转换为字符,因此找不到任何因素。
其次,在 apply
(AFAIK) 中无法访问列名,因此 names(x)
returns NULL
和 names(x)=="index"
returns logical(0)
。
让我有一个数据框,其中一些列 rae 因子类型,并且有一个名为 "index" 的列,它不是列。我想提取列
- 哪些是因子类型
- "index" 列。
例如让
df<-data.frame(a=runif(10),b=as.factor(sample(10)),index=as.numeri(1:10))
所以 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
期望的输出是(让它成为一个名为 df1 的数据框)
df1:
b index
5 1
8 2
3 3
2 4
9 5
1 6
10 7
6 8
7 9
4 10
其中包含因子列和名为 "index" 的列。
我用的是这样的代码
vars<-apply(df,2,function(x) {(is.factor(x)) || (names(x)=="index")})
df1<-df[,vars]
但是,此代码不起作用。我如何 return df1 在 R 中使用应用类型函数?我会很高兴任何帮助。非常感谢。
你可以这样做:
df[ , sapply(df, is.factor) | grepl("index", names(df))]
我认为您的方法有两个问题:首先,apply
将数据框转换为矩阵,矩阵不将值存储为因子(有关更多信息,请参阅
其次,在 apply
(AFAIK) 中无法访问列名,因此 names(x)
returns NULL
和 names(x)=="index"
returns logical(0)
。