Skip to content
Prev 359074 / 398502 Next

Extracting part of a factor

You mean this?
  test$place <- factor(test$place)

You can create a new column in a data frame by assigning something to it. E.g. 
   test$pollywog <- 1:6
... creates that column in "test".

But factor(test$place) was empty, because no such column previously existed, like:
R > factor(test$barbapapa)
factor(0)
Levels: 

So the right hand side has 0 rows, but the left hand side needs six. Of course you could create your column directly:

R > str(test)
'data.frame':	6 obs. of  6 variables:
 $ subject: Factor w/ 6 levels "001-002","002-003",..: 1 2 3 4 5 6
 $ group  : Factor w/ 2 levels "boys","girls": 1 1 1 2 2 2
 $ wk1    : int  2 7 9 5 2 1
 $ wk2    : int  3 6 4 7 6 4
 $ wk3    : int  4 5 6 8 3 7
 $ wk4    : int  5 4 1 9 8 4
R > test$place <- factor(substr(test$subject,1,3))    # here's were it gets done
R > str(test)
'data.frame':	6 obs. of  7 variables:
 $ subject: Factor w/ 6 levels "001-002","002-003",..: 1 2 3 4 5 6
 $ group  : Factor w/ 2 levels "boys","girls": 1 1 1 2 2 2
 $ wk1    : int  2 7 9 5 2 1
 $ wk2    : int  3 6 4 7 6 4
 $ wk3    : int  4 5 6 8 3 7
 $ wk4    : int  5 4 1 9 8 4
 $ place  : Factor w/ 6 levels "001","002","003",..: 1 2 3 4 5 6

... it's just that you insisted on mutate().



Cheers,
Boris
On Mar 4, 2016, at 9:31 PM, KMNanus <kmnanus at gmail.com> wrote: