user2788464 user2788464 - 1 month ago 15
R Question

Paste inside dataframe - R

In the dataset of InsectSprays there are 72 rows of 6 different sprays and I want to create another column inside this data.frame that will be the paste product of the spary code with its consecutive number (e.g., A_1…A_12, B_1…B_12,…).

I tried with the script below and how can I proceed.

data(InsectSprays)
df <- InsectSprays[1:2]
paste(rownames(df$spray), 1:nrow(df), sep="_")

Answer

We can use ave to create the sequence column

df$New <- with(df, paste(spray, ave(seq_along(spray), spray, FUN = seq_along), sep="_"))
Comments