How to map a column through a dictionary in R

前端 未结 2 1206
星月不相逢
星月不相逢 2021-01-18 10:47

I have a data frame in R. One column of this data frame takes values from 1 to 6. I have another data frame that maps this column. There is some way to substitute the values

2条回答
  •  [愿得一人]
    2021-01-18 11:35

    To use this type of map/dictionary to create a new data frame column, you can also use the match method:

    snape_gradebook_df<-data_frame(students=c("Harry", "Hermione", "Ron", "Neville", "Ginny", "Luna", "Draco", "Cho"),
               numeric_grade=c(4,2,2,3,4,1,4,4))
    grade_map<-data_frame(numbers=c(1,2,3,4), letters=c("A", "B", "C", "D"),
                        stringsAsFactors = FALSE)
    snape_gradebook_df['letter_grade']<-grade_map$letters[match(old_list, grade_map$numbers)]
    

    I'm not sure the advantages/disadvantages of setNames vs match - just thought I would share another possible solution.

提交回复
热议问题