Why there is NA after I replace the id with the actual value?

Hi,
I want to relpace the id number in"dataframe id" with it corresponding value in dta1. However, why the result in dta2 about id=981,990 is NA? i want to still use the way based on example code. Thank you for help in advance.

id<-data.frame(c(1,2,3,4,990,981))
dta1<-data.frame(id=c(1,2,3,4,5,6,980,981,990,991,992),
                 value=c(10.1,9.6,6.3,3.6,5.5,1.9,7.7,8.3,9.9,1.2,15.1))
colnames(id)<-"id"
lookup<-dta1$value
names(lookup)<-dta1$id
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
dta2<-id|>mutate(across(.cols = everything(),.fns = ~lookup[.x]))

Created on 2022-11-18 with reprex v2.0.2
image

The names of lookup are character, so adding as.character(.x) appears to give your intended result.

# names of lookup are character
names(lookup)
#>  [1] "1"   "2"   "3"   "4"   "5"   "6"   "980" "981" "990" "991" "992"

dta2 <-id |>
  mutate(across(.cols = everything(),
                .fns = ~lookup[as.character(.x)]))

dta2
#>     id
#> 1 10.1
#> 2  9.6
#> 3  6.3
#> 4  3.6
#> 5  9.9
#> 6  8.3

Created on 2022-11-18 with reprex v2.0.2.9000

1 Like

Thank you for your help, it works!My problem has been solved.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.