根据不同字段中的匹配和NA选择行

时间:2010-12-06 19:55:20

标签: r

在下面的示例中,我有两行,其中First,Last和Address 1/2匹配。两个不同的电子邮件地址,但有一个额外的自定义字段。我想要做的是系统地选择第一行,当呈现多个看起来像这样的行。

Lines <- "
First, Last, Address, Address 2, Email, Custom1, Custom2, Custom3
A, B, C, D, E@E.com,1,2,3
A, B, C, D, F@G.com,1,2,
"
con <- textConnection(Lines)

用语言说:

IF First&amp;最后&amp;地址1&amp;地址2匹配,选择custom3不是NA的那个。

我如何将其应用于大量数据?

注意:速度在​​这里并不重要,使用plyr的例子最有用。

2 个答案:

答案 0 :(得分:4)

以下是一些非plyr示例,因为我无法忍受有用。 ; - )

x <- read.csv(con)
close(con)

# Using split-apply-combine
do.call(rbind, lapply(split(x, x[,1:4]), function(X) X[!is.na(X$Custom3),]))

# Using ave
x[!ave(x$Custom3, x[,1:4], FUN=is.na),]

答案 1 :(得分:1)

这是一个plyr解决方案:

con <- textConnection(Lines <- "
First, Last, Address, Address 2, Email, Custom1, Custom2, Custom3
A, B, C, D, E@E.com,1,2,3
A, B, C, D, F@G.com,1,2,
")
x <- read.csv(con)
close(con)

ddply(x, .(First, Last, Address, Address.2), function(x2) x2[!is.na(x2$Custom3), c("Email", "Custom1", "Custom2", "Custom3")])