r - Create new variable -
i have data.frame contains 713 rows , 1 of it's columns itemcode has 228 unique codes. question is, how create choice selection ids?
nrow(test.1) [1] 713 length(unique(test.1$itemcode)) [1] 228 head(test.1) itemcode id 2 1180158001 1 225 1180149701 2 264 1180074301 3 522 1180177701 4 732 1180197201 5 1182 1170015601 6 here trial code:
test$id <- 1:nrow(test) (i in unique(test$itemcode)) (j in 1:length(unique(test$itemcode))) test$choice[test$itemcode == i] <- j my desired output this
itemcode id choice 2 1180158001 1 1 225 1180149701 2 2 264 1180074301 3 3 522 1180177701 4 4 732 1180197201 5 5 1182 1170015601 6 6 523 1180177701 7 4this works. if test.1 subset of test? code return underlaying values test.
test$choice <- as.integer( as.factor( test$itemcode ) )
i think want factor...
test$choice <- as.integer( as.factor( test$itemcode ) ) this turn each unique itemcodeinto integer coded variable. as.integer show underlying values are. if want them ordered appear in data.frame need specify levels of factor variable , can using factor rather as.factor.
# turn them integer code - ordering sorted on value of itemcode test$choice <- as.integer( as.factor( test$itemcode ) ) # same, specify ordering values appear in dataframe test$choice2 <- as.integer( factor( test$itemcode , levels = test$itemcode[ ! duplicated( test$itemcode ) ] ) ) itemcode id choice choice2 2 1180158001 1 4 1 225 1180149701 2 3 2 264 1180074301 3 2 3 522 1180177701 4 5 4 732 1180197201 5 6 5 1182 1170015601 6 1 6 523 1180177701 7 5 4
Comments
Post a Comment