Convert data.frame columns from factors to characters

前端 未结 18 1124
时光取名叫无心
时光取名叫无心 2020-11-22 04:43

I have a data frame. Let\'s call him bob:

> head(bob)
                 phenotype                         exclusion
GSM399350 3- 4- 8- 25- 44+         


        
18条回答
  •  长情又很酷
    2020-11-22 05:29

    Just following on Matt and Dirk. If you want to recreate your existing data frame without changing the global option, you can recreate it with an apply statement:

    bob <- data.frame(lapply(bob, as.character), stringsAsFactors=FALSE)
    

    This will convert all variables to class "character", if you want to only convert factors, see Marek's solution below.

    As @hadley points out, the following is more concise.

    bob[] <- lapply(bob, as.character)
    

    In both cases, lapply outputs a list; however, owing to the magical properties of R, the use of [] in the second case keeps the data.frame class of the bob object, thereby eliminating the need to convert back to a data.frame using as.data.frame with the argument stringsAsFactors = FALSE.

提交回复
热议问题