简体   繁体   中英

R rename adjacent column

When excel has merged cells importing the data gives generic column names for the subsequent columns as shown in the picture below.

R data frame from excel sheet with merged cells

So is it possible to copy the name of a column to the column to its right? In this example it would be copying "Sulfur dioxide Results" to overwrite X_6 and X_7, and "Ethanol Results" to X_8 and X_9 etc.

All the column names of interest end with "Results" so i'm considering if I can select the columns based on the "Results" in the name and copy the name to the 2 columns to its right.

There are many more columns, but they have the same pattern, and the amount of columns and their names are likely to change, but "Results" will still be in the names.

This solution works by using sapply against the names of a data frame. Then, for each column name, it checks if the name of the column which came either one or two positions prior ends in results . If so, then it copies over that previous name, from one or two positions prior.

df <- data.frame(one_results=c(1:3), blah=c(4:6), star=c(7:9), col=c(1:3))
df

names(df) <- sapply(seq_along(names(df)), function(x) {
    if (x > 1 && grepl("results$", names(df)[x-1])) {
        return(names(df)[x-1])
    }
    else if (x > 2 && grepl("results$", names(df)[x-2])) {
        return(names(df)[x-2])
    }
    else {
        return(names(df)[x])    # do not alter the column name in this case
    }
})

df

Output:

  one_results blah star col
1           1    4    7   1
2           2    5    8   2
3           3    6    9   3

  one_results one_results one_results col
1           1           4           7   1
2           2           5           8   2
3           3           6           9   3

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