簡體   English   中英

使用鍵替換R中數據框中的值

[英]Replace values in a data frame in R using a key

我有一個地方議會和縣的地理代碼數據集(geog_lookup)-它提供了哪個議會屬於哪個縣的密鑰。

我還有一個“混亂”的數據集(測試),該數據集可提供縣和市議會的信息,我想使用密鑰將其全部轉換為市議會。

有誰知道如何做到這一點? 到目前為止,這是我所擁有的?

 for (i in geog_lookup[,1]){ test[,1]<-replace(test[,1], n, value="i")} > head(geog_lookup) DataZone InterZone Council 1 S01000001 S02000003 S12000033 2 S01000002 S02000001 S12000033 3 S01000003 S02000001 S12000033 4 S01000004 S02000001 S12000033 5 S01000005 S02000003 S12000033 6 S01000006 S02000003 S12000033 > head(test) Location Year Reference.Area Dwellings.AC Dwellings.DE Dwellings.FH Total.Crime Hosp.Admissions House.Price 16 i 2008 S01000001 43.5 32.2 24.4 NA 1555 148500 17 i 2009 S01000001 43.5 32.2 24.4 NA 917 122750 18 i 2010 S01000001 44.3 31.7 24.0 NA 875 135000 19 i 2011 S01000001 44.0 31.5 24.5 NA 870 179000 20 i 2012 S01000001 44.3 31.1 24.6 NA 1174 155556 21 i 2013 S01000001 44.2 30.8 25.0 NA NA 118118 Job.Seekers Waste.Percapita Percent.Recycling Proximity.Derelict 16 0.350 NA NA 95.2 17 0.700 NA NA 95.2 18 0.325 NA NA 95.0 19 0.975 NA NA 95.0 20 0.650 NA NA 93.1 21 NA NA NA 90.9 

這是使用dplyr

library(dplyr)
test2 <- test %>%
  left_join(geog_lookup, by = c("Reference.Area" = "DataZone"))

這將進行數據庫geog_lookup (如Excel中的VLOOKUP),該聯接將從geog_lookup中添加列,其中的DataZone與您的源數據中的Reference.Area匹配。

這是基本的R解決方案。

merge(test, geog_lookup, by.x="Reference.Area", by.y="DataZone")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM