将数据帧列表中的列替换为另一个数据帧列表中的列。R

将数据帧列表中的列替换为另一个数据帧列表中的列。R,r,list,dataframe,tidyverse,purrr,R,List,Dataframe,Tidyverse,Purrr,我有两套清单,格式如下: list(list(structure(list(X = c(3L, 4L, 5L, 7L, 2L, 8L, 9L, 6L, 10L, 1L), Y = structure(c(2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L), .Label = c("no", "yes"), class = "factor")), .Names = c("X", "Y"), row.names = c(NA, -10L

我有两套清单,格式如下:

   list(list(structure(list(X = c(3L, 4L, 5L, 7L, 2L, 8L, 9L, 6L, 
    10L, 1L), Y = structure(c(2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 
    1L), .Label = c("no", "yes"), class = "factor")), .Names = c("X", 
    "Y"), row.names = c(NA, -10L), class = "data.frame"), structure(list(
        X = c(3L, 4L, 5L, 7L, 2L, 8L, 9L, 6L, 10L, 1L), Y = structure(c(2L, 
        2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L), .Label = c("no", "yes"
        ), class = "factor")), .Names = c("X", "Y"), row.names = c(NA, 
    -10L), class = "data.frame")))


我的目标是替换[[1]][[i]]$x我们可以使用
purrr
包中的
map2
来执行此替换
dat
是最终输出

library(purrr)

dat <- map2(a, b, function(x, y){
  map2(x, y, function(i, j){
    i[["X"]] <- j[["X"]]
    return(i)
  })
})

dat
# [[1]]
# [[1]][[1]]
#     X   Y
# 1  10 yes
# 2   3 yes
# 3   4  no
# 4   9 yes
# 5   8  no
# 6   2 yes
# 7   5  no
# 8   7  no
# 9   1 yes
# 10  6  no
# 
# [[1]][[2]]
#     X   Y
# 1   5 yes
# 2   7 yes
# 3   4  no
# 4   3 yes
# 5  10  no
# 6   2 yes
# 7   9  no
# 8   1  no
# 9   8 yes
# 10  6  no

mapply
解决方案可以简化一点,我认为-
a[[1]]map2是一个完美的解决方案。我不熟悉purrr,但我想我需要熟悉一下。只是一个问题:为什么没有返回(i)我会得到一个列替换而不是整个数据帧的列表?return(i)似乎是获得预期输出的必要条件。@JPV如果没有return,函数将假定您要返回在函数中创建的最后一个对象,在本例中是一列。如果有人对我的代码不起作用的原因有意见,我们将不胜感激,以便学习,今后不要再犯同样的错误。
df1$x<-df2$x
replacex<-function(onelist, anotherlist){

newlist<-list() #for storage
onelist$x<-anotherlist$x
newlist<-onelist 
}


Dfs_new_X<-lapply(a,lapply,replacex,anotherlist=b)
library(purrr)

dat <- map2(a, b, function(x, y){
  map2(x, y, function(i, j){
    i[["X"]] <- j[["X"]]
    return(i)
  })
})

dat
# [[1]]
# [[1]][[1]]
#     X   Y
# 1  10 yes
# 2   3 yes
# 3   4  no
# 4   9 yes
# 5   8  no
# 6   2 yes
# 7   5  no
# 8   7  no
# 9   1 yes
# 10  6  no
# 
# [[1]][[2]]
#     X   Y
# 1   5 yes
# 2   7 yes
# 3   4  no
# 4   3 yes
# 5  10  no
# 6   2 yes
# 7   9  no
# 8   1  no
# 9   8 yes
# 10  6  no
dat2 <- mapply(function(x, y){
  mapply(function(i, j){
    i[["X"]] <- j[["X"]]
    return(i)
  }, x, y, SIMPLIFY = FALSE)
}, a, b, SIMPLIFY = FALSE)

identical(dat, dat2)
# [1] TRUE