Get the Column Number in R Given the Column Name

Get the column number in R given the column name

which( colnames(df)=="b" )

Should do it.

Get column index from label in a data frame

you can get the index via grep and colnames:

grep("B", colnames(df))
[1] 2

or use

grep("^B$", colnames(df))
[1] 2

to only get the columns called "B" without those who contain a B e.g. "ABC".

How do I get the column number from a dataframe which contains specific strings?

You can use:

df[,match(z, substring(colnames(df), 1, 3))]

Get the name of one column by index in R

simply

colnames(df)[1]
[1] "name"

or

colnames(df[1])
[1] "name"

or

names(df[1])
[1] "name"

Get column index from data frame that matches numeric vector?

Here's a base R approach, which compares every column in dat with testVec to see if they are identical. Use which to output the column index if they're identical.

which(sapply(1:ncol(dat), function(x) identical(dat[,x], testVec)))
[1] 3

UPDATE
@nicola has provided a better syntax to my original code (you can see it in the comment under this answer):

which(sapply(dat, identical, y = testVec))
z
3

Get the column name and row name of a specific value in a dataframe

You may use which with arr.ind = TRUE to get row and column number where 5 is present. This can be changed to row and column names.

mat <- which(df == 5, arr.ind = TRUE)
paste('row : ', rownames(df)[mat[, 1]], 'column :', colnames(df)[mat[, 2]])
#[1] "row : 200 column : b"

refer to range of columns by name in R

A column number can be identified from a column name within a data frame as follows:

which(colnames(mydf)=="a")

where mydf is a data frame and a is the name of the column the column number is required for.

(Source)

This can be used to create a column range:

firstcol = which(colnames(x)=="a")
lastcol = which(colnames(x)=="b")

mydf[c(firstcol:lastcol)]

get column name that matches specific row value in dataframe

this is one method:

# construct sample data.frame
set.seed(1234)
df <- data.frame(matrix(
c(sample(1:4, 4), sample(1:4, 4),
sample(1:4, 4), sample(1:4, 4)),
ncol=4, byrow=T))
# name data.frame
names(df) <- c(paste0("x", 1:4))

# get names of variables
names(df)[apply(df, 1, function(i) which(i == 1))]

A method suggested by @DavidArenburg that is probably faster (especially for large datasets) is

names(df)[which(df == 1, arr.ind=T)[, "col"]]

because it does not need to use the apply function.

Note: I constructed a different data.frame as I don't have the permute package.



Related Topics



Leave a reply



Submit