This is an example of my initial table:
A35.Factor1 | A36.Factor2 |
---|---|
level1 | level3 |
level2 | level4 |
My desired output is:
Factor1 | Factor2 |
---|---|
A35.level1 | A36.level3 |
A35.level2 | A36. level4 |
My guess was to iterate through each column, extract the string through a regular expression and paste it using mutate() to the existing column, something like:
for(i in 1:ncol(dataset)) {
code <- colnames(dataset[,i])
code <- str_extract(code, "A[:digit:]")
dataset[ , i] <- dataset[, i] %>% mutate(dataset[,I] = paste(dataset[,i], code))
}
But it is not working, I guess I am reasoning in a bad way... thanks in advance!
CodePudding user response:
df[] <- mapply(paste0, gsub("\\..*", ".", names(df)), df)
names(df) <- gsub(".*\\.", "", names(df))
Factor1 Factor2
1 A35.level1 A36.level3
2 A35.level2 A36.level4
data
df <- read.table(header = T, text = "A35.Factor1 A36.Factor2
level1 level3
level2 level4")