Convert from lowercase to uppercase all values in all character variables in dataframe

前端 未结 7 754
萌比男神i
萌比男神i 2020-12-05 09:17

I have a mixed dataframe of character and numeric variables.

city,hs_cd,sl_no,col_01,col_02,col_03
Austin,1,2,,46,Female
Austin,1,3,,32,Male
Austin,1,4,,27,         


        
7条回答
  •  日久生厌
    2020-12-05 09:57

    A side comment here for those using any of these answers. Juba's answer is great, as it's very selective if your variables are either numberic or character strings. If however, you have a combination (e.g. a1, b1, a2, b2) etc. It will not convert the characters properly.

    As @Trenton Hoffman notes,

    library(dplyr)
    df <- mutate_each(df, funs(toupper))
    

    affects both character and factor classes and works for "mixed variables"; e.g. if your variable contains both a character and a numberic value (e.g. a1) both will be converted to a factor. Overall this isn't too much of a concern, but if you end up wanting match data.frames for example

    df3 <- df1[df1$v1 %in% df2$v1,]
    

    where df1 has been has been converted and df2 contains a non-converted data.frame or similar, this may cause some problems. The work around is that you briefly have to run

    df2 <- df2 %>% mutate_each(funs(toupper), v1)
    #or
    df2 <- df2 %>% mutate_each(df2, funs(toupper))
    #and then
    df3 <- df1[df1$v1 %in% df2$v1,]
    

    If you work with genomic data, this is when knowing this can come in handy.

提交回复
热议问题