Want to see only the chr variables (out of a list of chr and num variables) using str() function

71 Views Asked by At

I am using the following to get a sense of which variables are char, num, etc, and it works fine but now I'd like to see only those variables that R classifies as chr. Is there a path to doing so?

str(mtvtn, list.len = ncol(mtvtn))

I tried the following as well to no avail.

str(mtvtn, list = is.character(mtvtn))
2

There are 2 best solutions below

1
timnus On

Is this what you are after?

library(dplyr)
mtvtn %>% 
   select(where(is.character)) %>% 
   str(.)
2
jay.sf On

You need to subset.

str(dat[sapply(dat, is.character)])
# 'data.frame': 54 obs. of  2 variables:
#  $ wool   : chr  "A" "A" "A" "A" ...
#  $ tension: chr  "L" "L" "L" "L" ...

or

str(dat[sapply(dat, inherits, 'character')])
# 'data.frame': 54 obs. of  2 variables:
#  $ wool   : chr  "A" "A" "A" "A" ...
#  $ tension: chr  "L" "L" "L" "L" ...

Second version has the advantage that what can be a vector

str(dat[sapply(dat, inherits, c('character', 'integer'))])
# 'data.frame': 54 obs. of  3 variables:
#  $ breaks : int  26 30 54 25 70 52 51 26 67 18 ...
#  $ wool   : chr  "A" "A" "A" "A" ...
#  $ tension: chr  "L" "L" "L" "L" ...

Data:

dat <- type.convert(warpbreaks, as.is=TRUE)