[R] format selected columns in dataframe as character

Alain D. dialvac-r at yahoo.de
Thu Feb 26 11:08:57 CET 2015


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]]



More information about the R-help mailing list