Adding a prefix only to specific rows in dataframe R

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.


Fold_change


Well


A1


A2


Plate_1_


Plate_2_



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


[<-.factor


*tmp*




3 Answers
3



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])






Thank you for your help!

– vasdam
Sep 18 '18 at 9:21



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


Well


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)



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).


paste0


gsub


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



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)