简体   繁体   中英

How to prepend a string to column names for dataframe in R

I'm trying to relabel some columns of a dataframe object in R using a certain tag. I want to do a one liner like in In Python 3 (and 2) I would do this:

tag = "id_"
DF_data = pd.DataFrame(np.random.random((5,5)), columns = ["a","b","c","d","e"])
DF_data.columns = [tag + x for x in DF_data.columns]
DF_data.columns
# Index(['id_a', 'id_b', 'id_c', 'id_d', 'id_e'], dtype='object')

I tried it in R but I got an error

colnames(DF_data) = c(tag + x (for x in colnames(DF_data) )

This isn't working either

for (col_name in colnames(DF_data)){
    col_name = tag + col_name}

If I understand you correctly, you just want to add your tag to the beginning of each column name? If so:

colnames(DF_data) <- paste0(tag, colnames(DF_data))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM