Manipulating data in R: systematically replacing values ​​in a column with rows

I need to replace the values ​​in the column with the corresponding row. In my searches, I came across similar questions with answers that exactly match what I'm looking for, but nothing that exactly matches my needs. Since I'm a newbie, this will help if you can explain how this code works.

I want to move from a dataset like this

    A   B    C    D

1   1   64   20   1
2   2   64   20   3
3   3   64   20   3
4   4   64   20   1
5   5   64   20   2

To a dataset that looks like this using key 1 = Apple, 2 = Blastoise, 3 = Carousel

    A   B    C    D

1   1   64   20   Apple
2   2   64   20   Carousel
3   3   64   20   Carousel
4   4   64   20   Apple
5   5   64   20   Blastoise

I understand that you can just use something like

df$D <- "label"

to change the values ​​of a column.

However, I do not know how to get the "label" part to match the corresponding value.

Thank you in advance!

+4
2

baseR merge. -, dataframe, D :

labels <- data.frame(D=c(1,2,3), label=c("Apple", "Blastoise", "Carousel"))

:

result <- merge(df, labels, by="D")

result
  D A  B  C     label
1 1 1 64 20     Apple
2 1 4 64 20     Apple
3 2 5 64 20 Blastoise
4 3 2 64 20  Carousel
5 3 3 64 20  Carousel

, :

result <- merge(df, labels, by="D")[, union(names(df), names(labels))]
+2

:

D :

df$D - , 1, 2 3. . :

df$D = c(1,3,3,1,2)

:

v_names = c("Apple","Blastoise","Carousel")

, df$D v_names?

v_names[df$D]
[1] "Apple"     "Carousel"  "Carousel"  "Apple"     "Blastoise"

, , (df$D), , .

ifelse:

ifelse, , .

ifelse(df$D==1,"Apple",ifelse(df$D==2,"Blastoise","Carousel"))
[1] "Apple"     "Carousel"  "Carousel"  "Apple"     "Blastoise"

, ifelse. , .

, :

df$D = as.factor(df$D)
levels(df$D) = c("Apple","Blastoise","Carousel")

> df$D
[1] Apple     Carousel  Carousel  Apple     Blastoise
Levels: Apple Blastoise Carousel

, . - ,

df$D = as.character(df$D)
+1

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


All Articles