[R] R wildcards, sapply and as.factor
arun
smartpink111 at yahoo.com
Wed Nov 14 18:24:22 CET 2012
HI,
Try this:
df1<-read.table(text="
namestub1 namestub2 name1 name2
A1 B1 A11 B11
A1 B2 A11 B22
A2 B1 A22 B11
A2 B2 A22 B22
A3 B1 A33 B11
A3 B2 A33 B22
",sep="",header=TRUE,stringsAsFactors=FALSE)
str(df1)
#'data.frame': 6 obs. of 4 variables:
# $ namestub1: chr "A1" "A1" "A2" "A2" ...
# $ namestub2: chr "B1" "B2" "B1" "B2" ...
# $ name1 : chr "A11" "A11" "A22" "A22" ...
# $ name2 : chr "B11" "B22" "B11" "B22" ...
nm<-names(df1)[grepl("^namestub",names(df1))]
df1[nm]<-lapply(df1[nm],as.factor)
str(df1)
#'data.frame': 6 obs. of 4 variables:
# $ namestub1: Factor w/ 3 levels "A1","A2","A3": 1 1 2 2 3 3
# $ namestub2: Factor w/ 2 levels "B1","B2": 1 2 1 2 1 2
# $ name1 : chr "A11" "A11" "A22" "A22" ...
# $ name2 : chr "B11" "B22" "B11" "B22" ...
A.K.
----- Original Message -----
From: Fg Nu <fgnu32 at yahoo.com>
To: "r-help at r-project.org" <r-help at r-project.org>
Cc:
Sent: Wednesday, November 14, 2012 6:50 AM
Subject: [R] R wildcards, sapply and as.factor
I want to change the type to factor of all variables in a data frame whose names match a certain pattern.
So here I am trying to change the type to factor of all variables whose name begins with namestub in the dataframe df.
attach(df)sapply(grep(glob2rx("namestub*"),names(df)),as.factor)
But this doesn't work since
>levels(df$namestub1)NULL
______________________________________________
R-help at r-project.org mailing list
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