IT Share you

이름으로 여러 열 이름 바꾸기

shareyou 2020. 11. 25. 21:37
반응형

이름으로 여러 열 이름 바꾸기


누군가 이미이 질문을 했어야하는데 답을 찾을 수 없었습니다. 내가 가지고 있다고 :

x = data.frame(q=1,w=2,e=3, ...and many many columns...)  

위치를 알 필요가없는 임의의 열 하위 집합을 다른 임의의 이름으로 이름을 바꾸는 가장 우아한 방법은 무엇입니까?

예를 들어 말 나는 이름을 바꿀 "q""e""A"하고 "B",이 작업을 수행하는 가장 우아한 코드는 무엇인가?

분명히 루프를 수행 할 수 있습니다.

oldnames = c("q","e")
newnames = c("A","B")
for(i in 1:2) names(x)[names(x) == oldnames[i]] = newnames[i]

하지만 더 좋은 방법이 있는지 궁금합니다. 패키지 중 일부를 사용하고 있습니까? ( plyr::rename등)


setnames로부터 data.table패키지에서 작동 data.frames 또는 data.tableS

library(data.table)
d <- data.frame(a=1:2,b=2:3,d=4:5)
setnames(d, old = c('a','d'), new = c('anew','dnew'))
d


 #   anew b dnew
 # 1    1 2    4
 # 2    2 3    5

변경은 참조에 의해 이루어 지므로 복사하지 마십시오 (data.frame의 경우에도!).


dplyr을 사용하면 다음을 수행 할 수 있습니다.

library(dplyr)

df = data.frame(q = 1, w = 2, e = 3)

df %>% rename(A = q, B = e)

#  A w B
#1 1 2 3

또는 @ Jelena-bioinf가 제안한대로 벡터를 사용하려는 경우 :

library(dplyr)

df = data.frame(q = 1, w = 2, e = 3)

oldnames = c("q","e")
newnames = c("A","B")

df %>% rename_at(vars(oldnames), ~ newnames)

#  A w B
#1 1 2 3

너무 크지 않은 데이터 프레임에 대한 또 다른 솔루션은 (@thelatemail 답변을 기반으로 작성) 다음과 같습니다.

x <- data.frame(q=1,w=2,e=3)

> x
  q w e
1 1 2 3

colnames(x) <- c("A","w","B")

> x
  A w B
1 1 2 3

또는 다음을 사용할 수도 있습니다.

names(x) <- c("C","w","D")

> x
  C w D
1 1 2 3

또한 열 이름의 하위 집합의 이름을 바꿀 수도 있습니다.

names(x)[2:3] <- c("E","F")

> x
  C E F
1 1 2 3

그래서 최근에 열이 있는지 확실하지 않고 해당 열의 이름 만 바꾸고 싶다면 직접이 문제를 해결했습니다.

existing <- match(oldNames,names(x))
names(x)[na.omit(existing)] <- newNames[which(!is.na(existing))]

다음은 purrr::set_names()및 몇 가지 stringr작업을 조합하여 여러 열의 이름을 바꾸는 가장 효율적인 방법 입니다.

library(tidyverse)

# Make a tibble with bad names
data <- tibble(
    `Bad NameS 1` = letters[1:10],
    `bAd NameS 2` = rnorm(10)
)

data 
# A tibble: 10 x 2
   `Bad NameS 1` `bAd NameS 2`
   <chr>                 <dbl>
 1 a                    -0.840
 2 b                    -1.56 
 3 c                    -0.625
 4 d                     0.506
 5 e                    -1.52 
 6 f                    -0.212
 7 g                    -1.50 
 8 h                    -1.53 
 9 i                     0.420
 10 j                     0.957

# Use purrr::set_names() with annonymous function of stringr operations
data %>%
    set_names(~ str_to_lower(.) %>%
                  str_replace_all(" ", "_") %>%
                  str_replace_all("bad", "good"))

# A tibble: 10 x 2
   good_names_1 good_names_2
   <chr>               <dbl>
 1 a                  -0.840
 2 b                  -1.56 
 3 c                  -0.625
 4 d                   0.506
 5 e                  -1.52 
 6 f                  -0.212
 7 g                  -1.50 
 8 h                  -1.53 
 9 i                   0.420
10 j                   0.957

@ user3114046의 답변을 기반으로 작성 :

x <- data.frame(q=1,w=2,e=3)
x
#  q w e
#1 1 2 3

names(x)[match(oldnames,names(x))] <- newnames

x
#  A w B
#1 1 2 3

이는 x데이터 세트 의 특정 열 순서에 의존하지 않습니다 .


이렇게하면 모든 이름에서 해당 문자의 모든 발생이 변경됩니다.

 names(x) <- gsub("q", "A", gsub("e", "B", names(x) ) )

names(x)[names(x) %in% c("q","e")]<-c("A","B")

이름 세트를 가져 와서 목록으로 저장 한 다음 문자열에서 대량 이름을 바꿀 수 있습니다. 이에 대한 좋은 예는 데이터 세트에서 장기에서 전체로 전환하는 경우입니다.

names(labWide)
      Lab1    Lab10    Lab11    Lab12    Lab13    Lab14    Lab15    Lab16
1 35.75366 22.79493 30.32075 34.25637 30.66477 32.04059 24.46663 22.53063

nameVec <- names(labWide)
nameVec <- gsub("Lab","LabLat",nameVec)

names(labWide) <- nameVec
"LabLat1"  "LabLat10" "LabLat11" "LabLat12" "LabLat13" "LabLat14""LabLat15"    "LabLat16" " 

Lot's of sort-of-answers, so I just wrote the function so you can copy/paste.

rename <- function(x, old_names, new_names) {
    stopifnot(length(old_names) == length(new_names))
    # pull out the names that are actually in x
    old_nms <- old_names[old_names %in% names(x)]
    new_nms <- new_names[old_names %in% names(x)]

    # call out the column names that don't exist
    not_nms <- setdiff(old_names, old_nms)
    if(length(not_nms) > 0) {
        msg <- paste(paste(not_nms, collapse = ", "), 
            "are not columns in the dataframe, so won't be renamed.")
        warning(msg)
    }

    # rename
    names(x)[names(x) %in% old_nms] <- new_nms
    x
}

 x = data.frame(q = 1, w = 2, e = 3)
 rename(x, c("q", "e"), c("Q", "E"))

   Q w E
 1 1 2 3

Sidenote, if you want to concatenate one string to all of the column names, you can just use this simple code.

colnames(df) <- paste("renamed_",colnames(df),sep="")

If the table contains two columns with the same name then the code goes like this,

rename(df,newname=oldname.x,newname=oldname.y)

If one row of the data contains the names you want to change all columns to you can do

names(data) <- data[row,]

Given data is your dataframe and row is the row number containing the new values.

Then you can remove the row containing the names with

data <- data[-row,]

This is the function that you need: Then just pass the x in a rename(X) and it will rename all values that appear and if it isn't in there it won't error

rename <-function(x){
  oldNames = c("a","b","c")
  newNames = c("d","e","f")
  existing <- match(oldNames,names(x))
  names(x)[na.omit(existing)] <- newNames[which(!is.na(existing))]
  return(x)
}

참고URL : https://stackoverflow.com/questions/20987295/rename-multiple-columns-by-names

반응형