Subordinate character columns from a character and number data frame

I have a data frame consisting of numeric and non-numeric columns.

I would like to extract (a subset) of only non-numeric columns, therefore characteristic. Although I managed to multiply the numeric columns using the string:, sub_num = x[sapply(x, is.numeric)]I cannot do the opposite using the form is.character. Can anybody help me?

+3
source share
4 answers

Well, I briefly tried my idea.

I could confirm that the following code snippet works:

str(d)
 'data.frame':  5 obs. of  3 variables:
  $ a: int  1 2 3 4 5
  $ b: chr  "a" "a" "a" "a" ...
  $ c: Factor w/ 1 level "b": 1 1 1 1 1


# Get all character columns
d[, sapply(d, class) == 'character']

# Or, for factors, which might be likely:
d[, sapply(d, class) == 'factor']

# If you want to get both factors and characters use
d[, sapply(d, class) %in% c('character', 'factor')]

Using the correct class, your sapply-approach should work, at least until you enter the missing one ,before the function sapply.

!is.numeric , , numeric, factor, character (, POSIXct, )

+1

Try:

x[sapply(x, function(x) !is.numeric(x))]

- , .

EDIT:

x <- data.frame(a=runif(10), b=1:10, c=letters[1:10], 
    d=as.factor(rep(c("A", "B"), each=5)), 
    e=as.Date(seq(as.Date("2000/1/1"), by="month", length.out=10)),
    stringsAsFactors = FALSE)

# > str(x)
# 'data.frame':   10 obs. of  5 variables:
#  $ a: num  0.814 0.372 0.732 0.522 0.626 ...
#  $ b: int  1 2 3 4 5 6 7 8 9 10
#  $ c: chr  "a" "b" "c" "d" ...
#  $ d: Factor w/ 2 levels "A","B": 1 1 1 1 1 2 2 2 2 2
#  $ e: Date, format: "2000-01-01" "2000-02-01" ...

x[sapply(x, function(x) !is.numeric(x))]
0

Other previous answers are not so clear. Therefore, I am publishing this approach. To get character column names, you can do the following:

chrs <- sapply(df_data, is.character)
chrCols <- names(df_data[, chrs])
0
source

Using the @Tyler Example

x <- data.frame(a=runif(10), b=1:10, c=letters[1:10], 
    d=as.factor(rep(c("A", "B"), each=5)), 
    e=as.Date(seq(as.Date("2000/1/1"), by="month", length.out=10)),
    stringsAsFactors = FALSE)

In Base R

base::Filter(Negate(is.numeric),x)



   c d          e
1  a A 2000-01-01
2  b A 2000-02-01
3  c A 2000-03-01
4  d A 2000-04-01
5  e A 2000-05-01
6  f B 2000-06-01
7  g B 2000-07-01
8  h B 2000-08-01
9  i B 2000-09-01
10 j B 2000-10-01
0
source

All Articles