Create a new column based on the values ​​of other variables

I have data that looks like this:

Set of 10 character variables

Char<-c("A","B","C","D","E","F","G","H","I","J")

And a data frame that looks like

Col1<-seq(1:25)
Col2<-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5)
DF<-data.frame(Col1,Col2)

What I would like to do is add a third column to the data frame with logic 1 = A, 2 = B, 3 = C, etc. So the end result will be

Col3<-c("A","A","A","A","A","B","B","B","B","B","C","C","C","C","C","D","D","D","D","D","E","E","E","E","E")
DF<-data.frame(Col1,Col2,Col3)

For this simple example, I could go with a simple replacement similar to this question: Create a new column based on 4 values ​​in another column

But my actual dataset is much larger with a lot more variables than this simple example, so writing equivalents as in the answer above is not an option.

, . , -, Col2 Char.

1=Char[1]  2=Char[2] 3=Char[3]...... for the entire length of Col2

,

+4
4

, R, , .

for (i in length(DF$Col2)) {
    DF$Col3[i] <- Char[DF$Col2[i]]
}

? , unique(DF$Col2) levels(factor(DF$Col2))

, .

+3
# Values that Col2 might have taken
levels = c(1, 2, 3, 4, 5)

# Labels for the levels in same order as levels
labels = c('A', 'B', 'C', 'D', 'E')

DF$Col3 <- factor(DF$Col2, levels = levels, labels = labels)
+5

If you want to use each column as an index in some vector (I will use lettersit so that I can index up to 25), returning a data frame of the same size DF, you could use:

transformed <- as.data.frame(lapply(DF, function(x) letters[x]))
head(transformed)
#   Col1 Col2
# 1    a    a
# 2    b    a
# 3    c    a
# 4    d    a
# 5    e    a
# 6    f    b

You can then combine this with the original data frame with cbind(DF, transformed).

+3
source

Why not make a key and join?

library(dplyr)

letter_key = data_frame(letter__ID = 1:26,
                        letter = letters)

DF %>%
  rename(letter__ID = Col2) %>%
  left_join(letter_key)

This thing can also be done with the help of factors.

+3
source

Source: https://habr.com/ru/post/1608739/


All Articles