Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do add a column in a data frame in R

Tags:

r

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.

like image 582
sfactor Avatar asked Dec 30 '10 12:12

sfactor


People also ask

How do I add a new blank column to a Dataframe in R?

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.


1 Answers

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")
like image 190
nico Avatar answered Nov 14 '22 22:11

nico