R: How to change the column names in a data frame based on a specification

大兔子大兔子 提交于 2019-12-05 22:41:14

One way, where x is your df:

controls <- which(substring(names(x),4,4) %in% c("H","K"))
cases <- which(substring(names(x),4,4) %in% c("X","V"))
names(x)[controls] <- gsub("SM","Control",names(x)[controls])
names(x)[cases] <- gsub("SM","Case",names(x)[cases])

Alternatively:

names(x) <- sapply(names(x),function(z) {
    if(substring(z,4,4) %in% c("H","K"))
        sub("SM","Control",z)
    else if(substring(z,4,4) %in% c("X","V"))
        sub("SM","Case",z)
})

One-line alternative:

names(x) <- sub("^..(.(H|K))", "Control\\1", sub("^..(.(X|V))", "Case\\1", names(x))

First the names containing X and V are changed, then in the output string H and K containing names are changed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!