Change selected elements of character vector

前端 未结 4 1770
时光取名叫无心
时光取名叫无心 2021-01-24 17:04

Is there a shorter version for the folowing principle to rename certain columns of a data frame?

data1<-data.frame(\"a\"=1:3,\"b\"=1:3,\"c\"=1:3)

data1Names&         


        
相关标签:
4条回答
  • 2021-01-24 17:39

    Use match to replace selected elements and to respect the order when using names<-...

    names(data1)[ match( c("a", "c") , names(data1) ) ] <- c("hello", "world")
    #  hello b world
    #1     1 1     1
    #2     2 2     2
    #3     3 3     3
    

    Swapping the desired order of renaming...

    names(data1)[ match( c("c", "a") , names(data1) ) ] <- c("hello", "world")
    #  world b hello
    #1     1 1     1
    #2     2 2     2
    #3     3 3     3
    
    0 讨论(0)
  • 2021-01-24 17:47

    The data.table package has a setnames function that will work on data.frames

    library(data.table)
    data1<-data.frame("a"=1:3,"b"=1:3,"c"=1:3)
    #setnames(data1, "a", "hello")
    #setnames(data1, "c", "world")
    # or in one step
    setnames(data1, c("a", "c"), c("hello", "world"))
    data1
    #  hello b world
    #1     1 1     1
    #2     2 2     2
    #3     3 3     3
    

    All of the answers so far will make a copy of the data.frame. setnames has the added benefit that it changes the names by reference, without making a copy of the data.frame.

    0 讨论(0)
  • 2021-01-24 17:48

    setNames can be helpful

    > setNames(data1, c("hello", "b", "world"))
      hello b world
    1     1 1     1
    2     2 2     2
    3     3 3     3
    

    another alternative

    > names(data1)[names(data1) %in% c("a", "c")] <- c("hello", "world")
    > data1
      hello b world
    1     1 1     1
    2     2 2     2
    3     3 3     3
    
    0 讨论(0)
  • 2021-01-24 17:52

    You can use rename from the plyr package:

    data1<-data.frame("a"=1:3,"b"=1:3,"c"=1:3)
    > rename(data1,c('a' = 'hello','b' = 'world'))
      hello world c
    1     1     1 1
    2     2     2 2
    3     3     3 3
    
    0 讨论(0)
提交回复
热议问题