我正在寻找一种从另一个数据帧中的1个数据帧中查找信息的方法,从其他数据帧中获取值并将其传递回第一帧...
示例数据:
我有一个名为“x”的数据框
x <- structure(list(from = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L
), to = c(2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L), number = c(30,
30, 30, 33, 34, 35, 36, 37, 38, 39), name = c("region 1", "region 2",
"region 3", "region 4", "region 5", "region 6", "region 7", "region 8",
"region 9", "region 10")), .Names = c("from", "to", "number",
"name"), row.names = c(NA, -10L), class = "data.frame")
# from to number name
#1 1 2 30 region 1
#2 2 3 30 region 2
#3 3 4 30 region 3
#4 4 5 33 region 4
#5 5 6 34 region 5
#6 1 2 35 region 6
#7 2 3 36 region 7
#8 3 4 37 region 8
#9 4 5 38 region 9
#10 5 6 39 region 10
此数据框包含有关某些区域的信息(1-10)
我有另一个数据框“y”
y <- structure(list(location = c(1.5, 2.8, 10, 3.5, 2), id_number =
c(30, 30, 38, 40, 36)), .Names = c("location", "id_number"), row.names
= c(NA, -5L), class = "data.frame")
# location id_number
#1 1.5 30
#2 2.8 30
#3 10.0 38
#4 3.5 40
#5 2.0 36
这个包含有关位置的信息。
我需要的是一个函数(或命令,或者我可以在R中投掷的任何东西;-)): 对于y中的每一行:查找y $位置是否适合x $ from和x $到AND y $ id_number == x $ number。 如果找到一个匹配(一个位置y只能落在x行的一行中,或者在y中,则y不可能存在于y中的两行中),将x $ name返回到y中的一个新列,名为“name”
期望的输出:
# location id_number name
#1 1.5 30 region 1
#2 2.8 30 region 2
#3 10.0 38 <NA>
#4 3.5 40 <NA>
#5 2.0 36 region 7
我对R很新,所以我的第一个想法是使用for循环来解决这个问题(正如我以前在VB中所做的那样)。但后来我想:“noooooo”,我必须对它进行检验,就像所有人都告诉我优秀的R程序员一样; - )
所以我提出了一个函数,并用adply(来自plyr-package)调用它。 问题是:它不起作用,抛出一个我不明白的错误,现在我被卡住了......
有人能指出我正确的方向吗?
require("dplyr")
getValue <- function(y, x) {
tmp <- x %>%
filter(from <= y$location, to > y$location, number == y$id_number)
return(tmp$name)
}
y["name"] <- adply(y, 1, getValue, x=x)
答案 0 :(得分:2)
这是一个使用OP逻辑的简单基本方法:
f <- function(vec, id) {
if(length(.x <- which(vec >= x$from & vec <= x$to & id == x$number))) .x else NA
}
y$name <- x$name[mapply(f, y$location, y$id_number)]
y
# location id_number name
#1 1.5 30 region 1
#2 2.8 30 region 2
#3 10.0 38 <NA>
#4 3.5 40 <NA>
#5 2.0 36 region 7
答案 1 :(得分:2)
另一种基本方法(主要是):
# we need this for the last line - if you don't use magrittr, just wrap the sapply around the lapply
library(magrittr)
# get a list of vectors where each item is whether an item's location in y is ok in each to/from in x
locationok <- lapply(y$location, function(z) z >= x$from & z <= x$to)
# another list of logical vectors indicating whether y's location matches the number in x
idok <- lapply(y$id_number, function(z) z== x$number)
# combine the two list and use the combined vectors as an index on x$name
lapply(1:nrow(y), function(i) {
x$name[ locationok[[i]] & idok[[i]] ]
}) %>%
# replace zero length strings with NA values
sapply( function(x) ifelse(length(x) == 0, NA, x)
答案 2 :(得分:1)
由于您要匹配id_number
和number
的列,您可以在列上加入x
和y
,然后将名称变为{{1}如果位置不在NA
和from
之间,则此处为to
选项:
dplyr