94

我有一个大约 105000 行和 30 列的数据集。我有一个分类变量,我想将它分配给一个数字。在 Excel 中,我可能会使用VLOOKUP并填充。

我将如何去做同样的事情R

本质上,我所拥有的是一个HouseType变量,我需要计算HouseTypeNo. 以下是一些示例数据:

HouseType HouseTypeNo
Semi            1
Single          2
Row             3
Single          2
Apartment       4
Apartment       4
Row             3
4

9 回答 9

132

如果我正确理解了您的问题,这里有四种方法可以执行与 Excel 等效的操作VLOOKUP并使用以下方法填写R

# load sample data from Q
hous <- 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 the numbers to fill
# the large table
lookup <- unique(hous)
  HouseType HouseTypeNo
1      Semi           1
2    Single           2
3       Row           3
5 Apartment           4

以下是使用表格HouseTypeNolargetable的值填写的四种方法:lookup

首先merge在基地:

# 1. using base 
base1 <- (merge(lookup, largetable, by = 'HouseType'))

以命名向量为基础的第二种方法:

# 2. using base and a named vector
housenames <- 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 package
library(plyr)
plyr1 <- join(largetable, lookup, by = "HouseType")

四、使用sqldf

# 4. using the sqldf package
library(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)")

也需要对其他解决方案进行相应的更改。

那是你想做的吗?让我知道您喜欢哪种方法,我会添加评论。

于 2013-03-09T05:51:00.440 回答
33

我想你也可以使用match()

largetable$HouseTypeNo <- with(lookup,
                     HouseTypeNo[match(largetable$HouseType,
                                       HouseType)])

如果我打乱lookup.

于 2015-10-20T20:34:29.560 回答
11

我也喜欢使用qdapTools::lookup或速记二元运算符%l%。它的工作原理与 Excel vlookup 相同,但它接受与列号相反的名称参数

## 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
于 2013-10-22T12:50:53.287 回答
7

发帖人没有询问是否查找值 if exact=FALSE,但我将其添加为我自己和可能其他人参考的答案。

如果您正在查找分类值,请使用其他答案。

Excelvlookup还允许您将数值与第 4 个参数 (1) 近似匹配match=TRUE。我想像match=TRUE在温度计上查找值一样。默认值为 FALSE,非常适合分类值。

如果您想大致匹配(执行查找),R 有一个名为 的函数findInterval,它(顾名思义)将找到包含连续数值的区间/bin。

但是,假设您想要findInterval多个值。您可以编写一个循环或使用一个应用函数。但是,我发现采用 DIY 矢量化方法更有效。

假设您有一个由 x 和 y 索引的值网格:

grid <- list(x = c(-87.727, -87.723, -87.719, -87.715, -87.711), 
             y = c(41.836, 41.839, 41.843, 41.847, 41.851), 
             z = (matrix(data = c(-3.428, -3.722, -3.061, -2.554, -2.362, 
                                  -3.034, -3.925, -3.639, -3.357, -3.283, 
                                  -0.152, -1.688, -2.765, -3.084, -2.742, 
                                   1.973,  1.193, -0.354, -1.682, -1.803, 
                                   0.998,  2.863,  3.224,  1.541, -0.044), 
                         nrow = 5, ncol = 5)))

并且您有一些想要通过 x 和 y 查找的值:

df <- data.frame(x = c(-87.723, -87.712, -87.726, -87.719, -87.722, -87.722), 
                 y = c(41.84, 41.842, 41.844, 41.849, 41.838, 41.842), 
                 id = c("a", "b", "c", "d", "e", "f")

这是可视化的示例:

contour(grid)
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)

等高线图

您可以使用这种类型的公式找到 x 间隔和 y 间隔:

xrng <- range(grid$x)
xbins <- length(grid$x) -1
yrng <- range(grid$y)
ybins <- length(grid$y) -1
df$ix <- trunc( (df$x - min(xrng)) / diff(xrng) * (xbins)) + 1
df$iy <- trunc( (df$y - min(yrng)) / diff(yrng) * (ybins)) + 1

您可以更进一步,对 z 值执行(简单的)插值,grid如下所示:

df$z <- with(df, (grid$z[cbind(ix, iy)] + 
                      grid$z[cbind(ix + 1, iy)] +
                      grid$z[cbind(ix, iy + 1)] + 
                      grid$z[cbind(ix + 1, iy + 1)]) / 4)

这为您提供了这些值:

contour(grid, xlim = range(c(grid$x, df$x)), ylim = range(c(grid$y, df$y)))
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)
text(df$x + .001, df$y, lab=round(df$z, 2), col="blue", cex=1)

带值的等高线图

df
#         x      y id ix iy        z
# 1 -87.723 41.840  a  2  2 -3.00425
# 2 -87.712 41.842  b  4  2 -3.11650
# 3 -87.726 41.844  c  1  3  0.33150
# 4 -87.719 41.849  d  3  4  0.68225
# 6 -87.722 41.838  e  2  1 -3.58675
# 7 -87.722 41.842  f  2  2 -3.00425

请注意,ix 和 iy 也可以通过使用 的循环找到findInterval,例如,这是第二行的一个示例

findInterval(df$x[2], grid$x)
# 4
findInterval(df$y[2], grid$y)
# 2

哪个匹配ix并且iydf[2]

脚注: (1) vlookup 的第四个参数以前称为“match”,但在引入功能区后,它被重命名为“[range_lookup]”。

于 2015-12-11T18:04:34.670 回答
6

@Ben 答案的解决方案 #2在其他更通用的示例中不可重现。它恰好在示例中给出了正确的查找,因为唯一HouseType的 inhouses以递增的顺序出现。试试这个:

hous <- read.table(header = TRUE,   stringsAsFactors = FALSE,   text="HouseType HouseTypeNo
  Semi            1
  ECIIsHome       17
  Single          2
  Row             3
  Single          2
  Apartment       4
  Apartment       4
  Row             3")

largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)
lookup <- unique(hous)

Bens 解决方案#2 给出

housenames <- as.numeric(1:length(unique(hous$HouseType)))
names(housenames) <- unique(hous$HouseType)
base2 <- data.frame(HouseType = largetable$HouseType,
                    HouseTypeNo = (housenames[largetable$HouseType]))

unique(base2$HouseTypeNo[ base2$HouseType=="ECIIsHome" ])
[1] 2

当查找表中的正确答案是 17 时

正确的做法是

 hous <- read.table(header = TRUE,   stringsAsFactors = FALSE,   text="HouseType HouseTypeNo
      Semi            1
      ECIIsHome       17
      Single          2
      Row             3
      Single          2
      Apartment       4
      Apartment       4
      Row             3")

largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)

housenames <- tapply(hous$HouseTypeNo, hous$HouseType, unique)
base2 <- data.frame(HouseType = largetable$HouseType,
  HouseTypeNo = (housenames[largetable$HouseType]))

现在查找已正确执行

unique(base2$HouseTypeNo[ base2$HouseType=="ECIIsHome" ])
ECIIsHome 
       17

我试图编辑 Bens 的答案,但由于我无法理解的原因而被拒绝。

于 2013-12-09T19:08:47.863 回答
5

从...开始:

houses <- read.table(text="Semi            1
Single          2
Row             3
Single          2
Apartment       4
Apartment       4
Row             3",col.names=c("HouseType","HouseTypeNo"))

... 您可以使用

as.numeric(factor(houses$HouseType))

...为每种房屋类型提供唯一编号。你可以在这里看到结果:

> houses2 <- data.frame(houses,as.numeric(factor(houses$HouseType)))
> houses2
  HouseType HouseTypeNo as.numeric.factor.houses.HouseType..
1      Semi           1                                    3
2    Single           2                                    4
3       Row           3                                    2
4    Single           2                                    4
5 Apartment           4                                    1
6 Apartment           4                                    1
7       Row           3                                    2

...所以你最终会在行上得到不同的数字(因为这些因素是按字母顺序排列的)但模式相同。

(编辑:这个答案中的剩余文本实际上是多余的。我突然想到要检查一下,结果发现,read.table()当它首先被读入数据框时,已经使 house$HouseType 成为一个因素)。

但是,将 HouseType 转换为一个因子可能会更好,这会给您带来与 HouseTypeNo 相同的好处,但会更容易解释,因为房屋类型是命名的而不是编号的,例如:

> houses3 <- houses
> houses3$HouseType <- factor(houses3$HouseType)
> houses3
  HouseType HouseTypeNo
1      Semi           1
2    Single           2
3       Row           3
4    Single           2
5 Apartment           4
6 Apartment           4
7       Row           3
> levels(houses3$HouseType)
[1] "Apartment" "Row"       "Semi"      "Single"  
于 2013-03-08T21:30:09.483 回答
5

您可以mapvalues()从 plyr 包中使用。

初始数据:

dat <- data.frame(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"))

> dat
  HouseType
1      Semi
2    Single
3       Row
4    Single
5 Apartment
6 Apartment
7       Row

查找/人行横道表:

lookup <- data.frame(type_text = c("Semi", "Single", "Row", "Apartment"), type_num = c(1, 2, 3, 4))
> lookup
  type_text type_num
1      Semi        1
2    Single        2
3       Row        3
4 Apartment        4

创建新变量:

dat$house_type_num <- plyr::mapvalues(dat$HouseType, from = lookup$type_text, to = lookup$type_num)

或者对于简单的替换,您可以跳过创建长查找表并直接一步完成:

dat$house_type_num <- plyr::mapvalues(dat$HouseType,
                                      from = c("Semi", "Single", "Row", "Apartment"),
                                      to = c(1, 2, 3, 4))

结果:

> dat
  HouseType house_type_num
1      Semi              1
2    Single              2
3       Row              3
4    Single              2
5 Apartment              4
6 Apartment              4
7       Row              3
于 2015-10-20T20:37:18.243 回答
3

使用merge与 Excel 中的查找不同,因为如果未在查找表中强制执行主键约束,它可能会复制(乘以)您的数据,或者如果您不使用all.x = T.

为了确保您不会遇到麻烦并安全查找,我建议了两种策略。

第一个是检查查找键中的重复行数:

safeLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
  # Merges data to lookup making sure that the number of rows does not change.
  stopifnot(sum(duplicated(lookup[, by])) == 0)
  res <- merge(data, lookup[, c(by, select)], by = by, all.x = T)
  return (res)
}

这将迫使您在使用之前对查找数据集进行重复数据删除:

baseSafe <- safeLookup(largetable, house.ids, by = "HouseType")
# Error: sum(duplicated(lookup[, by])) == 0 is not TRUE 

baseSafe<- safeLookup(largetable, unique(house.ids), by = "HouseType")
head(baseSafe)
# HouseType HouseTypeNo
# 1 Apartment           4
# 2 Apartment           4
# ...

第二个选项是通过从查找数据集中获取第一个匹配值来重现 Excel 行为:

firstLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
  # Merges data to lookup using first row per unique combination in by.
  unique.lookup <- lookup[!duplicated(lookup[, by]), ]
  res <- merge(data, unique.lookup[, c(by, select)], by = by, all.x = T)
  return (res)
}

baseFirst <- firstLookup(largetable, house.ids, by = "HouseType")

lookup这些函数与添加多列时略有不同。

于 2016-05-21T23:03:54.827 回答
2

lookup软件包可以在这里使用:

library(lookup)
# reference data
hous <- data.frame(HouseType=c("Semi","Single","Row","Single","Apartment","Apartment","Row"),
                   HouseTypeNo=c(1,2,3,2,4,4,3))
# new large data with HouseType but no HouseTypeNo
largetable <- data.frame(HouseType = sample(unique(hous$HouseType), 1000, replace = TRUE))

# vector approach
largetable$num1 <- lookup(largetable$HouseType, hous$HouseType, hous$HouseTypeNo)
# dataframe approach
largetable$num2 <- vlookup(largetable$HouseType, hous, "HouseType", "HouseTypeNo")

head(largetable)
#   HouseType num1 num2
# 1      Semi    1    1
# 2      Semi    1    1
# 3 Apartment    4    4
# 4      Semi    1    1
# 5    Single    2    2
# 6    Single    2    2
于 2021-04-14T16:18:32.217 回答