将数据帧列表与字符列表配对

时间:2018-10-16 21:27:05

标签: r list dataframe vector

我有一个数据帧列表

df1=data.frame(yield=c(7,4,8),temp=c(25,28,30)) 
df2=data.frame(yield=c(6,5,8),temp=c(26,25,26))
df3=data.frame(yield=c(3,4,7),temp=c(31,28,27)) 

l1=list(df1,df2,df3)

和字符列表

l2=list("high N","mid N","low N")

我试图在每个数据帧中创建一个名为“ trt”的变量,并在其中填充字符列表的每个元素。

在一个数据帧上看起来像:

df1$trt=l2[[1]]

但是当我尝试使它变幻莫测时,我无法完全找到想要的东西。

我尝试过:

l3=lapply(l1,function(x) x$trt=l2)

l3=lapply(l1,function(x,y) x$trt=l2[[y]])

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

不太确定自己的预期,请尝试Map

Map(`[<-`, l1, i = "trt", value = l2)
  yield temp    trt
1     7   25 high N
2     4   28 high N
3     8   30 high N

[[2]]
  yield temp   trt
1     6   26 mid N
2     5   25 mid N
3     8   26 mid N

[[3]]
  yield temp   trt
1     3   31 low N
2     4   28 low N
3     7   27 low N

答案 1 :(得分:0)

或使用transform

Map(transform, l1, trt = l2)
#[[1]]
#  yield temp    trt
#1     7   25 high N
#2     4   28 high N
#3     8   30 high N

#[[2]]
#  yield temp   trt
#1     6   26 mid N
#2     5   25 mid N
#3     8   26 mid N

#[[3]]
#  yield temp   trt
#1     3   31 low N
#2     4   28 low N
#3     7   27 low N

有了tidyverse,我们可以使用mutate

library(tidyverse)
map2(l1, l2, ~ .x %>% 
                   mutate(trt = .y))