i new r , teaching myself how use it. i'm using r version 3.0.1 on windows 7 (if that's relevant).
i have trouble converting data of factors characters. data follows:
activity <- c("1","2","10","zz") what want have output
activity <- c("01","02","10","zz") where, each string, if contains 1 character, should prefixed 0 (as shown above).
i tried using "as.character" doesn't add 0 before. found sprintf , tried:
activity <- sprintf("%02d", (activity)) # [1] "01" "02" "03" "04" this adds 0 "0" in front of single data found what's troublesome modifies levels of data (as shown above).
does know what's wrong here , how can fix it? thank you.
you can use regular expressions, particularly function sub replace single digit 0 followed digit. should replace levels of factor activity whole data changed accordingly:
levels(activity) <- sub("^([0-9])$", "0\\1", levels(activity)) # [1] 01 02 10 zz # levels: 01 02 10 zz edit: if want not replace numbers string 1 character, can replace [0-9] .. is:
# suppose x is: x <- c("1", "a", "y", "!", "bb", "45") x <- factor(x, levels=unique(x)) levels(x) <- sub("^(.)$", "0\\1", levels(x)) # [1] 01 0a 0y 0! bb 45 # levels: 01 0a 0y 0! bb 45
Comments
Post a Comment