Issue: on appending a column as factor into data frame creates NA in appended column in r

It has nothing to do with pull().

You cannot convert a data.frame into a vector, even if there’s only 1 column:

X = subset(iris,select=-Species)
Y = subset(iris,select=Species)

as.factor(Y)
Species 
   <NA> 
Levels: 1:3

.valid.factor(Y)
[1] "factor levels must be \"character\""

levels(Y)
NULL

You need to call the column of the data.frame out:

X$y = as.factor(Y$Species)
# or X %>% mutate(y = as.factor(Y$Species))

> str(X)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ y           : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top