user2165857
user2165857

Reputation: 2690

Get the integer value of a level and add to new column

I have a factored list of elements in a dataframe such as:

df <- data.frame("A" = c(1, 2, 3, 4), "B" = c("a", "c", "d", "b"))

I reordered the factor levels in column "B" using:

levels(df$B) <- factor(df$B, levels = c("a", "b", "c", "d"))

I would like to access the level of a factor. For instance I would like to get the integer value for the level of "b" (which would be 2).

Additional Question:

I would also like to add a new column to my dataframe that will give the integer value of the level. In the above example this would give:

df <- data.frame("A" = c(1, 2, 3, 4), "B" = c("a", "c", "d", "b"), "Levels" =c(1,3,4,2))

Upvotes: 0

Views: 166

Answers (2)

Shambho
Shambho

Reputation: 3280

Method 1:

which(levels(df$B)=="b")

Method 2:

grep("b",levels(df$B))

Answer to additional question:

df <- cbind(df, "Levels" = as.numeric(df$B))

Upvotes: 4

Robert Krzyzanowski
Robert Krzyzanowski

Reputation: 9344

level_to_check <- 'b'; which(levels(df$B) == level_to_check) # 2

Upvotes: 2

Related Questions