vasdam
vasdam

Reputation: 15

Adding a prefix only to specific rows in dataframe R

I have a dataframe Fold_change with a column named Well with 576 variables that are named A1, A2...and so on. I would like to add the prefix Plate_1_ to the first 288 and the prefix Plate_2_ to the rest of the variables.

I looked around and I found this possible solution

Fold_change$Well <- paste0('Plate_1_', Fold_change$Well)

But the problem here is that changes the name to all variables

So I tried to specify the number of rows:

Fold_change$Well[1:288] <- paste0('Plate_1_', Fold_change$Well[1:288])

but I receive this error

Warning message: In [<-.factor(*tmp*, 1:288, value = c(NA, NA, NA, NA, NA, NA, : invalid factor level, NA generated

Upvotes: 0

Views: 858

Answers (3)

RLave
RLave

Reputation: 8364

Here's a possible solution, just change the row number values:

dat <- data.frame(
  col_a = paste0("A", 1:10)
)
dat #fake data, just 10 rows
# col_a
# 1     A1
# 2     A2
# 3     A3
# 4     A4
# 5     A5
# 6     A6
# 7     A7
# 8     A8
# 9     A9
# 10    A10

We can use paste0 to change values. And with gsub we can find the new pattern and update it just for the rows we want (5th to 10th in the example).

dat$col_a <- paste0("Plate_1_", dat$col_a) #changes names for all
dat$col_a[5:length(dat$col_a)] <- gsub("Plate_1_", "Plate_2_",dat$col_a[5:length(dat$col_a)]) 
#updates only for last 6 values
dat
# col_a
# 1  Plate_1_A1
# 2  Plate_1_A2
# 3  Plate_1_A3
# 4  Plate_1_A4
# 5  Plate_2_A1
# 6  Plate_2_A2
# 7  Plate_2_A3
# 8  Plate_2_A4
# 9  Plate_2_A5
# 10 Plate_2_A6

Upvotes: 0

Istrel
Istrel

Reputation: 2588

Try to convert the Well column to string first. Then perform manipulation and if needed convert it back to factor.

Fold_change$Well <- as.character(Fold_change$Well)
Fold_change$Well[1:288] <- paste0('Plate_1_', Fold_change$Well[1:288])
# anithing else
Fold_change$Well <- as.factor(Fold_change$Well)

Upvotes: 0

nghauran
nghauran

Reputation: 6768

Try:

Fold_change$Well <- as.character(Fold_change$Well) # change column class from factor to character first
Fold_change$Well[1:288] <- paste0('Plate_1_', Fold_change$Well[1:288])

Upvotes: 1

Related Questions