如何在R中完成VLOOKUP和填充(如Excel)?我有一个大约105000行30列的数据集。我有一个分类变量,我想把它分配给一个数字。在Excel中,我可能会用VLOOKUP然后填满。我要怎么做同样的事R?本质上,我所拥有的是HouseType变量,我需要计算HouseTypeNo..以下是一些样本数据:HouseType HouseTypeNoSemi 1Single 2Row 3Single 2Apartment 4Apartment 4Row 3
3 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
VLOOKUP
R
:
# load sample data from Qhous <- read.table(header = TRUE, stringsAsFactors = FALSE, text="HouseType HouseTypeNo Semi 1 Single 2 Row 3 Single 2 Apartment 4 Apartment 4 Row 3")# create a toy large table with a 'HouseType' column # but no 'HouseTypeNo' column (yet)largetable <- data.frame( HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)# create a lookup table to get t he numbers to fill# the large tablelookup <- unique(hous) HouseType HouseTypeNo1 Semi 12 Single 23 Row 35 Apartment 4
HouseTypeNo
largetable
lookup
merge
# 1. using base base1 <- (merge(lookup, largetable, by = 'HouseType'))
# 2. using base and a named vectorhousenames <- as.numeric(1:length(unique(hous$HouseType)))names(housenames) <- unique(hous$HouseType)base2 <- data.frame(HouseType = largetable$HouseType, HouseTypeNo = (housenames[largetable$HouseType]))
plyr
# 3. using the plyr packagelibrary(plyr)plyr1 <- join(largetable, lookup, by = "HouseType")
sqldf
# 4. using the sqldf packagelibrary(sqldf)sqldf1 <- sqldf("SELECT largetable.HouseType, lookup.HouseTypeNo FROM largetable INNER JOIN lookup ON largetable.HouseType = lookup.HouseType")
largetable
lookup
sqldf("select * from largetable left join lookup using (HouseType)")
手掌心
TA贡献1942条经验 获得超3个赞
match()
:
largetable$HouseTypeNo <- with(lookup, HouseTypeNo[match(largetable$HouseType, HouseType)])
lookup
.
不负相思意
TA贡献1777条经验 获得超10个赞
qdapTools::lookup
%l%
## Replicate Ben's data:hous <- structure(list(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"), HouseTypeNo = c(1L, 2L, 3L, 2L, 4L, 4L, 3L)), .Names = c("HouseType", "HouseTypeNo"), class = "data.frame", row.names = c(NA, -7L))largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)## It's this simple:library(qdapTools)largetable[, 1] %l% hous
- 3 回答
- 0 关注
- 859 浏览
添加回答
举报
0/150
提交
取消