I have imported data from a file into a data frame in R. It is something like this.
Name Count Category
A 100 Cat1
C 10 Cat2
D 40 Cat1
E 30 Cat3
H 3 Cat3
Z 20 Cat2
M 50 Cat10
So now i want to add the Category column depending on the values in the column Name. So something like if Name = (A, D), Category = 'Cat1' etc.
This is only a simple example I am giving. I have a large number of Names and Categories so I want a compact syntax. How can I do this?
Edit: I've changed the example to better suit my needs as the name can be anything not numeric. Sorry for not being too clear before.
To add an empty column in R, use cbin() function. This function takes a DataFrame as a first argument and an empty column you wanted to add as a second argument. Note that this doesn't update the existing DataFrame instead it returns a copy of the DataFrame after adding an empty column.
You can use ifelse
. If your data frame were called df
you would do:
df$cat <- ifelse(df$name<100, "Ones", "Hundreds")
df$cat <- ifelse(df$name<1000, df$cat, "Thousands")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With