dataframe - R transform column with string as character, not as factor -
i curious behaviour of transform. 2 ways might try creating new column character not factor:
x <- data.frame(letters = letters[1:3], numbers = 1:3) y <- transform(x, alphanumeric = as.character(paste(letters, numbers))) x$alphanumeric = with(x, as.character(paste(letters, numbers))) x y str(x$alphanumeric) str(y$alphanumeric) the results "look" same:
> x letters numbers alphanumeric 1 1 1 2 b 2 b 2 3 c 3 c 3 > y letters numbers alphanumeric 1 1 1 2 b 2 b 2 3 c 3 c 3 but inside , 1 has worked:
> str(x$alphanumeric) # did convert character chr [1:3] "a 1" "b 2" "c 3" > str(y$alphanumeric) # transform didn't factor w/ 3 levels "a 1","b 2","c 3": 1 2 3 i didn't find ?transform useful explain behaviour - presumably alphanumeric coerced being factor - or find way stop (something stringsasfactors = false data.frame). safest way this? there similar pitfalls beware of, instance apply or plyr functions?
this not issue transform as data.frames, stringsasfactors set, default, true. add argument should false , you'll on way:
y <- transform(x, alphanumeric = paste(letters, numbers), stringsasfactors = false) str(y) # 'data.frame': 3 obs. of 3 variables: # $ letters : factor w/ 3 levels "a","b","c": 1 2 3 # $ numbers : int 1 2 3 # $ alphanumeric: chr "a 1" "b 2" "c 3" i use within instead of transform, , seems not have problem:
y <- within(x, { alphanumeric = paste(letters, numbers) }) str(y) # 'data.frame': 3 obs. of 3 variables: # $ letters : factor w/ 3 levels "a","b","c": 1 2 3 # $ numbers : int 1 2 3 # $ alphanumeric: chr "a 1" "b 2" "c 3" this because takes approach similar with approach: create character vector , add (via [<-) existing data.frame.
you can view source of each of these typing transform.data.frame , within.data.frame @ prompt.
as other pitfalls, that's broad of question. 1 thing comes mind right waya apply create matrix data.frame, columns coerced single type.
Comments
Post a Comment