Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace given index of a vector in a column by the values of the vector

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading