Home > other >  Replace given index of a vector in a column by the values of the vector
Replace given index of a vector in a column by the values of the vector

Time:11-18

I am struggling with this supposedly simply task:

updated df: I have this data frame:

df<- structure(list(Species = c("setosa", "not_setosa", "setosa", 
"setosa", "setosa", "setosa"), index = c(4L, 3L, 2L, 5L, 1L, 
3L)), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6"))

     Species index
1     setosa     4
2 not_setosa     3
3     setosa     2
4     setosa     5
5     setosa     1
6     setosa     3

and this vector:

my_vector <- c("one", "two", "three", "four", "five", "six")

[1] "one"   "two"   "three" "four"  "five"  "six"  

I would like to replace the values in the index column df$index with the values of the corresponding indices in the vector my_vector

The expected output:

     Species index
1     setosa  four
2 not_setosa three
3     setosa   two
4     setosa  five
5     setosa   one
6     setosa three

I have tried many variations with which and match but did not come to an end. I also tried with factors but was not successful.

CodePudding user response:

You can simply index my_vector by the values in df$index.

df$index = my_vector[df$index]

Output:

     Species index
1     setosa  four
2 not_setosa three
3     setosa   two
4     setosa  five
5     setosa   one
6     setosa three

Input:

structure(list(Species = c("setosa", "not_setosa", "setosa", 
"setosa", "setosa", "setosa"), index = c("four", "three", "two", 
"five", "one", "three")), row.names = c(NA, -6L), class = "data.frame")
  • Related