将列表的第一个元素与另一个列表进行比较

时间:2014-11-03 15:19:03

标签: r list

我正在使用R并需要一个提示来解决我的问题:

我有两个列表,我想比较列表第一行的值" a"使用列表第一行的值" b"。如果元素存在,我想写第二行列表的值" b"进入第二行列表" a"。

所以,这是列表" a":

X.WORD    FREQ
abase     0
abased    0
abasing   0
abashs    0

此处列出" b"

V1        V2
arthur    11
abased    29
turtle    9
abash     2

结果应为

X.WORD    FREQ
abase     0
abased    29
abasing   0
abashs    0

感谢您的回答

2 个答案:

答案 0 :(得分:3)

这只是基础R中简单merge的任务

Res <- merge(a, b, by.x = "X.WORD", by.y = "V1", all.x = TRUE)[, -2]
Res$V2[is.na(Res$V2)] <- 0
Res
#    X.WORD V2
# 1   abase  0
# 2  abased 29
# 3  abashs  0
# 4 abasing  0

数据

a <- structure(list(X.WORD = structure(c(1L, 2L, 4L, 3L), .Label = c("abase", 
"abased", "abashs", "abasing"), class = "factor"), FREQ = c(0L, 
0L, 0L, 0L)), .Names = c("X.WORD", "FREQ"), class = "data.frame", row.names = c(NA, 
-4L))

b <- structure(list(V1 = structure(c(3L, 1L, 4L, 2L), .Label = c("abased", 
"abash", "arthur", "turtle"), class = "factor"), V2 = c(11L, 
29L, 9L, 2L)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, 
-4L))

答案 1 :(得分:1)

这是一种方法。

library(dplyr)

ana <- foo %>%
    left_join(foo2, by = c("X.WORD" = "V1")) %>%
    select(-FREQ) %>%
    rename(FREQ = V2)

ana$FREQ[is.na(ana$FREQ)] <- 0

#   X.WORD FREQ
#1   abase    0
#2  abased   29
#3 abasing    0
#4  abashs    0

数据

foo <- structure(list(X.WORD = structure(c(1L, 2L, 4L, 3L), .Label = c("abase", 
"abased", "abashs", "abasing"), class = "factor"), FREQ = c(0L, 
0L, 0L, 0L)), .Names = c("X.WORD", "FREQ"), class = "data.frame", row.names = c(NA, 
-4L))

foo2 <- structure(list(V1 = structure(c(3L, 1L, 4L, 2L), .Label = c("abased", 
"abash", "arthur", "turtle"), class = "factor"), V2 = c(11L, 
29L, 9L, 2L)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, 
-4L))