Home Create a new variable based on existing data
Reply: 1

Create a new variable based on existing data

beckylllin1992 Published in 2017-11-14 21:23:00Z

I have a variable called "Item", it contains data looks like "1, A, 2, B, 3, C, 4, D, 5, E, 6, F". The data type of this variable is a list. I would like to create a new factor variable called "Item type", which contains two values, either "numbers" or "letters".

So ideal dataset looks like this

Item     Item type
1        numbers
A        letters
2        numbers
B        letters
3        numbers
C        letters
4        numbers
D        letters

I'm having trouble to create the new variable "item type". I have tried a couple ways to do that. It seems like my data type of "item" is a list, so it wouldn't allow me to create a new factor. Does anyone can help me with it? A sample code would be helpful! Thank you!

PoGibas Reply to 2017-11-14 21:41:54Z

Please try this (your table should be called df):

df$`Item type` <- ifelse(grepl("[0-9]", df$Item), "numbers", "letters")

Here I use grep to find if string contains number and ifelse to return numbers if it does or letters if it doesn't.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.311831 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO