본문 바로가기
통계프로그램 비교 시리즈/데이터 전처리 비교

통계프로그램 비교 시리즈 – [데이터 관리] 5. 변수명 변경(Rename)

by 기서무나구물 2022. 1. 10.

포스팅 목차

    [데이터 관리] 5. 변수명 변경(Rename)

     


    1. Proc SQL

     

    • 변수명 변경을 위한 SQL(PROC SQL)프로그램.
    • 일반 오라클에서는 상단의 별칭(as)을 통한 변수명을 새롭게 지정하여서 변경할 수 있다.
    SAS Programming
    proc sql;
      create table withmooc as
        select id,
               workshop,
               gender,
               q1 as x1,
               q2 as x2,
               q3 as x3,
               q4 as x4
        from   BACK.mydata;
    quit;
    
    proc sql;
      create table withmooc as
        select *
        from   BACK.mydata(rename=(q1-q4=x1-x4));
    quit;
    
    proc sql;
      create table withmooc(rename=(q1-q4=x1-x4)) as
        select *
        from   BACK.mydata;
    quit;
    
    proc sql;
      create table withmooc as
        select *
        from   BACK.mydata(rename=(q1=x1 q2=x2 q3=x3 q4=x4));
    quit;
    
    proc print;run;

     

     


    2. SAS Programming

     

    • Rename 함수를 사용하여 변수명 변경;
    SAS Programming
    DATA withmooc;
     set BACK.mydata;
         RENAME q1=x1  q2=x2  q3=x3  q4=x4;
    RUN;
    
    # Rename 함수를 사용하여 동시에 변수명 변경;
    DATA withmooc;
     set BACK.mydata;
         RENAME q1-q4=x1-x4;
    RUN;
    
    # 출력 데이터에서 데이터명 변경;
    DATA withmooc(rename=(q1-q4=x1-x4));
     set BACK.mydata;
    RUN;
    
    
    # 입력 데이터에서 데이터명 변경;
    DATA withmooc;
     set BACK.mydata(rename=(q1-q4=x1-x4));
    RUN;
    
    proc print;run;

     

    Results
    id    workshop    gender    x1    x2    x3    x4
     1        1         f        1     1     5     1
     2        2         f        2     1     4     1
     3        1         f        2     2     4     3
     4        2         f        3     1     .     3
     5        1         m        4     5     2     4
     6        2         m        5     4     5     5
     7        1         m        5     3     4     4
     8        2         m        4     5     5     5

     

     


    3. SPSS

     

    SPSS Programming
    GET FILE='C:\mydata.sav'.
    
    RENAME VARIABLES (Q1=X1)(Q2=X2)(Q3=X3)(Q4=X4).
    
    EXECUTE.

     

     


    4. R Programming (R-PROJECT)

     

    R Programming
    from rpy2.robjects import r
    %load_ext rpy2.ipython

     

    Results
    The rpy2.ipython extension is already loaded. To reload it, use:
      %reload_ext rpy2.ipython

     


     

    R Programming
    %%R
    library(tidyverse)
    load(file="C:/work/data/mydata.Rdata")
    
    withmooc = mydata
    attach(withmooc) # mydata를 기본 데이터 세트로 지정.
    
    withmooc

     

    Results
    R[write to console]: The following objects are masked from withmooc (pos = 3):
    
        gender, q1, q2, q3, q4, workshop
    
    
    R[write to console]: The following objects are masked from withmooc (pos = 4):
    
        gender, q1, q2, q3, q4, workshop
    
    
    
    
      workshop gender q1 q2 q3 q4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


    R Program for Renaming Variables.

    • 데이터 에디터 화면을 이용한 변수명 변경.
    • 스프레트 쉬트에서 변수명을 클릭 후 변경 후에 쉬트를 닫는다.
    R Programming
    %%R
    fix(withmooc)
    
    withmooc

     

    Results
      workshop gender q1 q2 q3 q4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


    Rename함수 사용.

     

    R Programming
    %%R
    
    withmooc = mydata

     


    • 이 방법은 이해하기 쉬우나, 실제 구현 방법을 이해하는데 돕지 않는다.
    • rename함수를 적용하기 위하여 Reshape 라이브러리를 다운로드.
    R Programming
    %%R
    
    # install.packages("reshape")
    library(reshape)
    
    withmooc <- rename(withmooc, c(q1="x1")) #Note the new name is one in quotes.
    withmooc <- rename(withmooc, c(q2="x2"))
    withmooc <- rename(withmooc, c(q3="x3"))
    withmooc <- rename(withmooc, c(q4="x4"))
    
    withmooc

     

    Results
      workshop gender x1 x2 x3 x4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


    • 패키지 이용 없이 변경하는 간단한 방법.
    • names함수를 사용하여서 변수명 순서대로 변수명을 나열하는 방법.
    R Programming
    %%R
    
    withmooc = mydata
    
    names(withmooc) <- c("group", "gender", "x1", "x2", "x3", "x4")
    
    withmooc

     

    Results
      group gender x1 x2 x3 x4
    1     1      f  1  1  5  1
    2     2      f  2  1  4  1
    3     1      f  2  2  4  3
    4     2      f  3  1 NA  3
    5     1      m  4  5  2  4
    6     2      m  5  4  5  5
    7     1      m  5  3  4  4
    8     2      m  4  5  5  5

     

     


    5. R - Tidyverse

     

    R Programming
    from rpy2.robjects import r
    %load_ext rpy2.ipython

     

    Results
    The rpy2.ipython extension is already loaded. To reload it, use:
      %reload_ext rpy2.ipython

     


     

    R Programming
    %%R
    
    library(tidyverse)
    load(file="C:/work/data/mydata.Rdata")
    
    withmooc = mydata
    
    attach(withmooc) # mydata를 기본 데이터 세트로 지정.
    
    withmooc

     

    Results
    R[write to console]: The following objects are masked from withmooc (pos = 4):
    
        gender, q1, q2, q3, q4, workshop
    
    
    R[write to console]: The following objects are masked from withmooc (pos = 5):
    
        gender, q1, q2, q3, q4, workshop
    
    
    R[write to console]: The following objects are masked from withmooc (pos = 6):
    
        gender, q1, q2, q3, q4, workshop
    
    
    
    
      workshop gender q1 q2 q3 q4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


    Select 구문을 사용하여서 변수명 변경

     

    R Programming
    %%R
    
    withmooc %>%
      select(x1 = q1,x2 = q2,x3 = q3, x4 = q4)

     

    Results
      x1 x2 x3 x4
    1  1  1  5  1
    2  2  1  4  1
    3  2  2  4  3
    4  3  1 NA  3
    5  4  5  2  4
    6  5  4  5  5
    7  5  3  4  4
    8  4  5  5  5

     


    Rename 구문을 사용하여 변수명 변경

     

    R Programming
    %%R
    
    library(tidyverse)

     

     

    R Programming
    %%R
    
    withmooc = mydata
    
    withmooc %>%
      dplyr::rename(x1 = q1,x2 = q2,x3 = q3, x4 = q4)

     

    Results
      workshop gender x1 x2 x3 x4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


    • 변수명에서 문자 q를 문자 x로 변경
    R Programming
    %%R
    
    withmooc %>% 
      dplyr::rename_all(funs(sub('q', 'x' , .)))

     

    Results
      workshop gender x1 x2 x3 x4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


    • 변수명에서 문자 q를 문자 x로 변경
    R Programming
    %%R
    
    withmooc %>%
      dplyr::rename_with(~ gsub("q", "x", .x, fixed = TRUE))

     

    Results
      workshop gender x1 x2 x3 x4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


     

    R Programming
    %%R
    
    withmooc %>%
      rename_at(vars(starts_with('q')), funs(sub('q', 'x' , .)))

     

    Results
      workshop gender x1 x2 x3 x4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


     

    R Programming
    %%R
    
    withmooc %>%
      rename_at(vars(starts_with("q")), funs(str_replace(., "q", "x")))

     

    Results
      workshop gender x1 x2 x3 x4
    1        1      f  1  1  5  1
    2        2      f  2  1  4  1
    3        1      f  2  2  4  3
    4        2      f  3  1 NA  3
    5        1      m  4  5  2  4
    6        2      m  5  4  5  5
    7        1      m  5  3  4  4
    8        2      m  4  5  5  5

     


    [참고] 접두어 일괄 추가

     

    R Programming
    %%R
    
    withmooc %>% 
      rename_at(vars(starts_with('q')), funs(paste0('back_', .)))

     

    Results
      workshop gender back_q1 back_q2 back_q3 back_q4
    1        1      f       1       1       5       1
    2        2      f       2       1       4       1
    3        1      f       2       2       4       3
    4        2      f       3       1      NA       3
    5        1      m       4       5       2       4
    6        2      m       5       4       5       5
    7        1      m       5       3       4       4
    8        2      m       4       5       5       5

     


    • [참고] 지정한(q) 변수에 인덱스 번호 추가하여 변수명 변경.
    R Programming
    %%R
    
    withmooc %>%
      rename_all( ~ str_replace(., "q", paste0("var", seq_along(.),'_')))

     

    Results
      workshop gender var3_1 var4_2 var5_3 var6_4
    1        1      f      1      1      5      1
    2        2      f      2      1      4      1
    3        1      f      2      2      4      3
    4        2      f      3      1     NA      3
    5        1      m      4      5      2      4
    6        2      m      5      4      5      5
    7        1      m      5      3      4      4
    8        2      m      4      5      5      5

     

     


    6. Python - Pandas

     

    Python Programming
    import pandas as pd
    import numpy as np
    import sweetviz as sv
    from IPython.display import display  # DataFrame()을 HTML로 출력
    
    mydata   = pd.read_csv("C:/work/data/mydata.csv",sep=",",
                           dtype={'id':object,'workshop':object,
                                  'q1':int, 'q2':int, 'q3':float, 'q4':int},
                           na_values=['NaN'],skipinitialspace =True)
    
    withmooc= mydata.copy()
    
    withmooc

     

    Results
    	id	workshop	gender	q1	q2	q3	q4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5
     

    Rename함수 사용.

    • 이 방법은 이해하기 쉬우나, 실제 구현 방법을 이해하는데 돕지 않는다.
    • rename함수를 적용하기 위하여 Reshape 라이브러리를 다운로드.
    Python Programming
    withmooc= mydata.copy()
    withmooc
    
    withmooc = withmooc.rename(index=str, columns={"q1": "x1","q2": "x2","q3": "x3","q4": "x4"})
    withmooc

     

    Results
    	id	workshop	gender	x1	x2	x3	x4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5
     
     

    • 패키지 이용없이 변경하는 간단한 방법.

    names함수를 사용하여서 나열하기 위한 순서대로 변수명을 나열하는 방법.

    Python Programming
    withmooc= mydata.copy()
    withmooc
    
    withmooc.columns = ['id','workshop','gender','x1','x2','x3','x4']
    withmooc

     

    Results
    	id	workshop	gender	x1	x2	x3	x4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5
     
     

    • q로 시작하는 변수명을 일괄적으로 x로 변경
    Python Programming
    withmooc= mydata.copy()
    withmooc
    
    withmooc.columns = withmooc.columns.str.replace('q','x')
    withmooc

     

    Results
    	id	workshop	gender	x1	x2	x3	x4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5
     

    • q로 시작하는 변수명을 일괄적으로 x로 변경
    Python Programming
    withmooc= mydata.copy()
    withmooc
    
    # q로 시작하는 변수명에서 문자 "q"를 제거
    withmooc.columns = withmooc.columns.str.lstrip('q')
    display(withmooc)
    
    # 변수명 앞에 일괄적으로 문자 추가
    withmooc = withmooc.add_prefix('x_')
    display(withmooc)
    
    # 변수명 뒤에 일괄적으로 문자 추가
    withmooc = withmooc.add_suffix('_y')
    withmooc

     

    Results
    	id	workshop	gender	1	2	3	4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5

     

    Results
    	x_id	x_workshop	x_gender	x_1	x_2	x_3	x_4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5​
    Results
    	x_id_y	x_workshop_y	x_gender_y	x_1_y	x_2_y	x_3_y	x_4_y
    0	1	1		f		1	1	5.0	1
    1	2	2		f		2	1	4.0	1
    2	3	1		f		2	2	4.0	3
    3	4	2		f		3	1	NaN	3
    4	5	1		m		4	5	2.0	4
    5	6	2		m		5	4	5.0	5
    6	7	1		m		5	3	4.0	4
    7	8	2		m		4	5	5.0	5​
     

    • 참고 ( 변수명에 접두어 접미어 추가하기.)
    Python Programming
    withmooc= mydata.copy()
    withmooc
    
    # q로 시작하는 변수명에서 문자 "q"를 제거
    withmooc.columns = withmooc.columns.str.lstrip('q')
    display(withmooc)
    
    # Lambda 함수를 사용하여서 일괄적으로  접두어 'x_' 와 접미어 '_y' 를 추가하기.
    withmooc.rename(columns = lambda x: "x_" + x + "_y", inplace = True)
    
    withmooc

     

    Results
    	id	workshop	gender	1	2	3	4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5

     

    Results
    	x_id_y	x_workshop_y	x_gender_y	x_1_y	x_2_y	x_3_y	x_4_y
    0	1	1		f		1	1	5.0	1
    1	2	2		f		2	1	4.0	1
    2	3	1		f		2	2	4.0	3
    3	4	2		f		3	1	NaN	3
    4	5	1		m		4	5	2.0	4
    5	6	2		m		5	4	5.0	5
    6	7	1		m		5	3	4.0	4
    7	8	2		m		4	5	5.0	5​
     

    • 행 인덱스 번호를 이용하는 방법.
    • 먼저 names함수를 이용하여 변수명을 추출.
    Python Programming
    withmooc= mydata.copy()
    withmooc
    
    mynames = list(withmooc.columns)
    print(mynames)
    
    mynames[3] = "T1"
    mynames[4] = "T2"
    mynames[5] = "T3"
    mynames[6] = "T4"
    
    withmooc.columns = mynames
    
    withmooc

     

    Results
    ['id', 'workshop', 'gender', 'q1', 'q2', 'q3', 'q4']

     

    Results
    	id	workshop	gender	T1	T2	T3	T4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5
     

    • 각 변수의 순서. 즉 V1은 column [2]
    Python Programming
    withmooc= mydata.copy()
    withmooc
    
    mynames = list(withmooc.columns)
    print(mynames)
    
    mynames[mynames.index("q1")] = 'x1'
    mynames[mynames.index("q2")] = 'x2'
    mynames[mynames.index("q3")] = 'x3'
    mynames[mynames.index("q4")] = 'x4'
    
    withmooc.columns = mynames
    
    withmooc

     

    Results
    ['id', 'workshop', 'gender', 'q1', 'q2', 'q3', 'q4']

     

    Results
    	id	workshop	gender	x1	x2	x3	x4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5

     


    • 기존 변수명을 대체할 변수명 생성
    Python Programming
    withmooc= mydata.copy()
    withmooc
    
    # 기존 변수명을 대체할 변수명 생성.
    myXs = ["x" + str(x + 1) for x in range(4)]
    print(myXs)
    
    mylist = list(withmooc.columns)
    myA = mylist.index("q1")
    print(myA)
    myZ = mylist.index("q4")
    print(myZ)
    
    
    withmooc.columns = list(withmooc.iloc[:,:myA].columns) + myXs
    
    withmooc

     

    Results
    ['x1', 'x2', 'x3', 'x4']
    3
    6

     

    Results
    	id	workshop	gender	x1	x2	x3	x4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5
     

     


    7. Python - dfply

     

    Python Programming
    import pandas as pd
    from dfply import *
    
    mydata   = pd.read_csv("c:/work/data/mydata.csv",sep=",",
                                                dtype={'id':object,'workshop':object,
                                                       'q1':int, 'q2':int, 'q3':float, 'q4':int},
                                                na_values=['NaN'],skipinitialspace =True)
    
    withmooc= mydata.copy()
    
    # 모든 변수 선택하기.
    withmooc

     

    Results
    	id	workshop	gender	q1	q2	q3	q4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5
     

    • Rename함수 사용.
    • 이 방법은 이해하기 쉬우나, 실제 구현 방법을 이해하는데 돕지 않는다.
    • rename함수를 적용하기 위하여 Reshape 라이브러리를 다운로드.
    Python Programming
    withmooc >> rename(x1 = X.q1,x2 = X.q2,x3 = X.q3, x4 = X.q4)

     

    Results
    	id	workshop	gender	x1	x2	x3	x4
    0	1	1		f	1	1	5.0	1
    1	2	2		f	2	1	4.0	1
    2	3	1		f	2	2	4.0	3
    3	4	2		f	3	1	NaN	3
    4	5	1		m	4	5	2.0	4
    5	6	2		m	5	4	5.0	5
    6	7	1		m	5	3	4.0	4
    7	8	2		m	4	5	5.0	5

     

     

     


     


     

    통계프로그램 비교 목록(Proc sql, SAS, SPSS, R 프로그래밍, R Tidyverse, Python Pandas, Python Dfply)
    [Oracle, Pandas, R Prog, Dplyr, Sqldf, Pandasql, Data.Table] 오라클 함수와 R & Python 비교 사전 목록 링크
    [SQL, Pandas, R Prog, Dplyr, SQLDF, PANDASQL, DATA.TABLE]
    SQL EMP 예제로 만나는 테이블 데이터 처리 방법 리스트 링크
    반응형

    댓글