How to get the name of a variable isolated from data.frame using indexing?

Given a variable isolated from a data frame, how do I get its name? It should work in functions where indexing is done internally (e.g. applied).

df<-data.frame(a=1:10,b=1:10)

names(df[,1])

gives:

>NULL

test<-df[,1]
test[0]

Here is an example where this might be useful:

library(plyr)
relabel<-colwise(function(column){
  column<-paste(names(column),column)})
relabel(df)

gives

data.frame(a=c(.1,.2,.3,...), b=c(.1,.2,...))

Desired Results:

data.frame(a=c('a.1','a.2','a.3'), b=c('b.1','b.2', 'b.2'))
+3
source share
1 answer

Use the argument drop = FALSEin indexing, as in:

df<-data.frame(a=1:10,b=1:10)

names(df[,1, drop=FALSE])

Here is a function that performs what you are looking for:

namer.guy <- function(x) paste(rep(names(x), nrow(x)),  unlist(x), sep=".")

namer.guy(df[, 1, drop=F])

Edit: by Etienne's request Low-Decarie ...

namer.guy2 <- function(df){
    name.paster <- function(i) paste(names(df)[i], df[, i], sep=".")
    DF <- data.frame(sapply(seq_along(df), name.paster))
    names(DF) <- names(df)
    return(DF)
}

namer.guy2(df)
+4
source

All Articles