根据列查找不同的数据帧

时间:2016-06-01 19:19:35

标签: r

假设我有以下数据框:

d1 <- data.frame(index = c(1,2,3,4), location = c('barn', 'house', 'restaurant', 'tomb'), random = c(5,3,2,1), different_col1 = c(66,33,22,11))
d2 <- data.frame(index = c(1,2,3,4), location = c('server', 'computer', 'home', 'dictionary'), random = c(1,7,2,9), differen_col2 = c('hi', 'there', 'different', 'column'))

我要做的是根据索引获取位置以及它是什么数据帧。所以我有以下内容:

data <- data.frame(src = c('one', 'one', 'two', 'one', 'two'), index = c(1,4,2,3,2))

其中src表示数据应来自哪个数据框,index表示indexindex中的值。

src  |  index
-------------
one  |    1
one  |    4
two  |    2
one  |    3
two  |    2

我希望它成为:

src  | index | location
-----------------------
one  |   1   | barn
one  |   4   | tomb
two  |   2   | computer
one  |   3   | restaurant
two  |   2   | computer

由于我的数据大小,我希望避免merge或类似的联接(sqldf等)。

4 个答案:

答案 0 :(得分:5)

以下是使用data.table按引用添加新列的一种方法:

require(data.table)
setDT(d1); setDT(d2); setDT(data) # convert all data.frames to data.tables

data[src == "one", location := d1[.SD, location, on="index"]]
data[src == "two", location := d2[.SD, location, on="index"]]

.SD代表数据子集,并包含data中与i - 参数中提供的条件匹配的所有列。

有关详情,请参阅vignettes

您也可以在match右侧的表达式中使用:=,而不是使用location提取join。但如果你想在多列上匹配,它就不可扩展。

答案 1 :(得分:0)

library(dplyr)
mutate(data,
       location = ifelse(src == "one", 
                         as.character(d1[index, "location"]),
                         as.character(d2[index, "location"])))

输出

  src index   location
1 one     1       barn
2 one     4       tomb
3 two     2   computer
4 one     3 restaurant
5 two     2   computer

答案 2 :(得分:0)

$(function() { $('#nav li a').click(function() { $('#nav li').removeClass(); $($(this).attr('href')).addClass('active'); }); }); 将帮助您更有效地处理大数据。

您可以使用data.tablematch的特殊data.table实现,这比我原始解决方案的合并要快得多,正如我们在评论中所讨论的那样。

以下是一个例子:

merge

答案 3 :(得分:-1)

基本解决方案:使用字符索引选择正确的数据帧,然后使用mapply处理多个“并行参数”的提交。

 dput(dat)
structure(list(src = c("one", "one", "two", "one", "two"), X. = c("|", 
"|", "|", "|", "|"), index = c(1L, 4L, 2L, 3L, 2L), location = structure(c(1L, 
4L, 5L, 3L, 5L), .Label = c("barn", "house", "restaurant", "tomb", 
"computer", "dictionary", "home", "server"), class = "factor")), .Names = c("src", 
"X.", "index", "location"), row.names = c(NA, -5L), class = "data.frame")

可能需要使用stringsAsFactor来确保字符参数。

dat$location <- mapply(function(whichd,i) dlist[[whichd]][i,'location'], whichd=dat$src, i=dat$index)

> dat
  src X. index   location
1 one  |     1       barn
2 one  |     4       tomb
3 two  |     2   computer
4 one  |     3 restaurant
5 two  |     2   computer
>