-2

如何在str(dataframe)的输出中识别dataframe的哪个columnname是“chr”?

 df = read.table(myfile.txt)
 str(df)

换句话说,如何知道数据框中每一列的类型?> str(df)

 >>>str(df)
'data.frame':   5 obs. of  6 variables:
 $ gender: Factor w/ 2 levels "F","M": 2 1 2 2 2
 $ age   : num  51.1 51.5 52.3 54 52.4
 $ Col1  : int  46 47 45 38 41
 $ Col2  : int  38 NA 38 40 27
 $ Col3  : num  0.6 0.4 0.9 0.8 0.8
 $ col4  : int  1 1 1 1 0
4

1 回答 1

0
> df <- data.frame(V1=letters[1:20], V2=rnorm(20), V3=rnorm(20), stringsAsFactors=F)
> head(df)
  V1         V2         V3
1  a -1.1503207  0.6404503
2  b  0.8197962  0.5596914
3  c -0.9807482 -0.9668770
4  d -0.7739147 -0.0118510
5  e -0.1544853  0.6315314

> names(df)[(1:ncol(df))[mapply(is.character, df)]]
[1] "V1"

根据@Tyler Rinker 上面提供的建议:

> names(df)[sapply(df, class)=="character"]
[1] "V1"

如果您想简单地删除 chr 列:

> df2 <- df[,sapply(df, class)!="character"]
> head(df2)
            V2         V3
1  -1.15032068  0.6404503
2   0.81979620  0.5596914
3  -0.98074820 -0.9668770
4  -0.77391472 -0.0118510
5  -0.15448529  0.6315314
于 2013-07-18T20:01:03.073 回答