Using a 2-column mapping dataframe in R to change values in main dataframe

后端 未结 2 440
情话喂你
情话喂你 2021-01-24 10:45

Apologies if this is a duplicate question, I have a feeling it has been asked, but I will provide a good example to help with understanding this. First the demo dataframes:

相关标签:
2条回答
  • 2021-01-24 10:55

    Another way would be to use your map_df as a look-up table.

    rownames(map_df) = map_df$name
    main_df$P1 = map_df[main_df$P1, "id"]
    main_df$P2 = map_df[main_df$P2, "id"]
    
    0 讨论(0)
  • 2021-01-24 11:08

    We can use match. Loop over the columns with lapply, match with 'name' column of 'map_df' and use the numeric index to change the values to the corresponding 'id' in 'map_df', assign the output to 'main_df'

    main_df[] <- lapply(main_df, function(x) map_df$id[match(x, map_df$name)])
    

    Or convert it to a matrix and match it

    main_df[] <- setNames(map_df$id, map_df$name)[as.matrix(main_df)]
    
    0 讨论(0)
提交回复
热议问题