如何使用 r 将列表中的值从米转换为公里(来自 html_nodes)?

How can I convert values from meters to km in a list (from html_nodes) with r?

我有以下列表来自

distance_to_center <- html_nodes(HouseRentingPage, xpath = '//*[@class="distance"]')
distance_to_center <- html_text(distance_to_center)

(ps: 是部分列表——原来有3000多条观察)

 distance_to_center

[1]"822 m" "500 m" "12.8 km" "435 m" NA "1 km" "985 m" "3.5 km" "4.9 km" "623 m"

如何将以米为单位的值转换为千米?我尝试使用 if 语句,但它不起作用。

试试这个

#Identifying the values in meter
chk <-  grep(" m", distance_to_center)

#Converting m into km
distance_to_center[chk] <- paste(as.numeric(gsub(".*?([0-9]+).*", "\1", 
                                                 distance_to_center[chk]))/1000, 
                                 "km")  
distance_to_center

[1] "0.822 km" "0.5 km"   "12.8 km"  "0.435 km" NA         "1 km"     "0.985 km" "3.5 km"   "4.9 km"   "0.623 km"