[R] format selected columns in dataframe as character

MacQueen, Don macqueen1 at llnl.gov
Thu Feb 26 17:05:09 CET 2015


Of course you could have created them as character vectors in the first
place:

dfx <- data.frame(
  group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
  sex = sample(c("M", "F"), size = 29, replace = TRUE),
  age = runif(n = 29, min = 18, max = 54),
  stringsAsFactors=FALSE
  )


But if that is not possible in your context, then I would suggest this:

for (nm in names(dfx))
   if (is.factor(dfx[[nm]])) dfx[[nm]] <- as.character(dfx[[nm]])

It's clear and simple.



-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 2/26/15, 2:08 AM, "Alain D." <dialvac-r at yahoo.de> wrote:

>Dear R-List,
> 
>#I have a df with the first two cols formatted as factor.
> 
>dfx <- data.frame(
>group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
>sex = sample(c("M", "F"), size = 29, replace = TRUE),
>age = runif(n = 29, min = 18, max = 54))
> 
># now I want to format both factor VARs as character
># I tried
> 
>factor.id<-names(dfx[sapply(dfx,is.factor)])
>chr.names<-which(names(dfx)%in% factor.id)
> 
>dfx[ , chr.names]<-as.character(dfx[ , chr.names])
># which gives me
>str(dfx)
>'data.frame': 29 obs. of 3 variables: $ group: chr "c(1, 1, 1, 1, 1, 1,
>1, 1, 2,
>2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3)" "c(2, 2, 1,
>1, 1,
>1, 2, 1, 1, 2, 2, 1, 2, 2, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 2, 2)"
>"c(1,
>1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3,
>3, 3, 3,
>3)" "c(2, 2, 1, 1, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2, 1, 1, 1, 1, 1, 2, 1,
>1, 1,
>1, 1, 2, 2, 2)" ... $ sex : chr "c(2, 2, 1, 1, 1, 1, 2, 1, 1, 2, 2, 1, 2,
>2, 2,
>1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 2, 2)" "c(1, 1, 1, 1, 1, 1, 1, 1, 2,
>2, 2,
>2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3)" "c(2, 2, 1, 1, 1,
>1, 2,
>1, 1, 2, 2, 1, 2, 2, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 2, 2)" "c(1,
>1, 1,
>1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,
>3, 3)"
>... $ age : num 38.5 18 33.5 26 22.5 ...
> 
>#though I was hoping for something like
> 
>'data.frame': 29 obs. of  3 variables:
>$ group: chr  "A" "A" "A" "A" ...
>$ sex  : chr  "M" "F" "F" "M" ...
>$ age  : num  21.3 35.2 53.8 21 23.6 ...
>
>#What is wrong with my code?
>#Thank you for any help
>
>Best wishes 
>
>Alain
> 
> 
> 
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list