Convert data.frame columns from factors to characters

前端 未结 18 1425
时光取名叫无心
时光取名叫无心 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:21

    Or you can try transform:

    newbob <- transform(bob, phenotype = as.character(phenotype))
    

    Just be sure to put every factor you'd like to convert to character.

    Or you can do something like this and kill all the pests with one blow:

    newbob_char <- as.data.frame(lapply(bob[sapply(bob, is.factor)], as.character), stringsAsFactors = FALSE)
    newbob_rest <- bob[!(sapply(bob, is.factor))]
    newbob <- cbind(newbob_char, newbob_rest)
    

    It's not good idea to shove the data in code like this, I could do the sapply part separately (actually, it's much easier to do it like that), but you get the point... I haven't checked the code, 'cause I'm not at home, so I hope it works! =)

    This approach, however, has a downside... you must reorganize columns afterwards, while with transform you can do whatever you like, but at cost of "pedestrian-style-code-writting"...

    So there... =)

提交回复
热议问题