R programming
2
0
Entering edit mode
2.3 years ago

Hey everyone,

So I have a dataframe with two columns, one being a list of antibiotics and another one quantity. I have an excel sheet from which I'm extracting the concentration of drugs, say something like 100mg. I then split 100 mg to 100 and mg seperately and wanna add the 100 to the quantity column of the dataframe. This works fine.

Now, if I want to add another value to the same row in the same column, how do i do that?

For example: now my dataframe looks like this:

Antibiotic    quantity
azithromycin    100

And If i wanna add another 100 to the quantity, and make it like this:

Antibiotic    quantity
azithromycin    200

How do I do that? Could someone help me out please?

Many thanks in advance Anjali

programming dataframe r • 790 views
ADD COMMENT
2
Entering edit mode
2.3 years ago

hard to say without seeing the data.frame

if it's named df and the antibiotics are row.names

## (will add 100 to every cell in the row)
df['azithromycin',] <- df['azithromycin',]+100 


## (will add 100 to first column)
df['azithromycin',1] <- df['azithromycin',1]+100 

If it's named df but there are separate columns

df$quantity[match('azithromycin',df$Antibiotic),'quantity'] <- df$quantity[match('azithromycin',df$Antibiotic),'quantity']+100

In all cases I assume at bare minimum the column names are quantity and antibiotic

ADD COMMENT
0
Entering edit mode

Hi thanks for this.

I tried rbind() and i guess it wokrs, so the syntax i gave is:

Prescription_concentrations_output$Quantity[2] <- rbind(Prescription_concentrations_output$Quantity[2]+200)
ADD REPLY
1
Entering edit mode
2.3 years ago
acvill ▴ 350

Using the mutate function from the dplyr package, you can add values conditionally:

# create mock dataset

df <- data.frame(Antibiotic = rep(c("azithromycin", "doxycycline", "ciprofloxacin"), each = 3),
                 quantity = rep(c(100, 200, 300), 3))

# if antibiotic is azithromycin, add 100 to quantity

df <- dplyr::mutate(df, quantity = ifelse(Antibiotic == "azithromycin",
                                          yes = quantity + 100,
                                          no = quantity))
ADD COMMENT

Login before adding your answer.

Traffic: 1933 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6