从列表的数据帧中获取相同的列,并分配给另一个列表的数据帧

时间:2017-03-29 01:52:22

标签: r list dataframe

我有一个数据框列表,其中列表中的所有数据框都具有相同的列名。例如,列表A:

dfA1 <- data.frame(x1 = c("a", "b"), y1 = c(1, 2), z1 = c(10, 12))
dfA2 <- data.frame(x1 = c("c", "d"), y1 = c(3, 4), z1 = c(20, 22))
dfA3 <- data.frame(x1 = c("c", "d"), y1 = c(3, 4), z1 = c(30, 32))
dfA4 <- data.frame(x1 = c("e", "f"), y1 = c(5, 6), z1 = c(40, 42))

listA <- list(dfA1, dfA2, dfA3, dfA4)

我有另一个相同数量的数据帧列表,这些数据帧具有相同的行数和相同的列。例如,ListB:

dfB1 <- data.frame(x1 = c("c", "d"))
dfB2 <- data.frame(x1 = c("a", "b"))
dfB3 <- data.frame(x1 = c("c", "d"))
dfB4 <- data.frame(x1 = c("e", "f"))

listB <- list(dfB1, dfB2, dfB3, dfB4)

我想从listA的数据帧中取出y1列,并根据列x1添加到listB的数据帧。怎么做?

1 个答案:

答案 0 :(得分:0)

I solved the problem differently. Now I would extract two columns (i.e. the common column and the new column to add into new list. Then I would merge the two lists. My new code is: few.col <- lapply(listA, '[', c('x1', 'y1'))

相关问题