使用for循环将新数据追加到列表的每个数据帧元素时,我遇到了困难。
如果我有一个包含两个数据帧的列表(文件列表),并且希望“ dplyr :: left_join”或“合并”列表中的每个数据帧与单个数据帧中的其他数据,那么它似乎没有出现在列表中。但是,如果我对列表中的每个数据框元素分别逐步使用相同的命令,则会收到相同的警告(由于缺少因子级别),但可获得预期的结果。例如:
df1 <- data.frame(x = 1:3, y=letters[1:3])
df2 <- data.frame(x = 1:5, y=letters[1:5])
# make list of dataframes
filelist <- list(df1,df2)
# new data frame to add to the data frames in the list by indexing "y"
df3 <- data.frame(animal = c(rep("snake", 7)), y=letters[1:7], geno = c("aa", "ab", "ac", "aa", "ac", "ab", "ae"))
# merge df3 into both data frames in the filelist
for (i in 1:length(filelist)) {dplyr::left_join(filelist[[i]], df3, by = "y")}
## Gives the following warning because some factor levels are missing between datasets
Warning message:
Column `y` joining factors with different levels, coercing to character vector
> filelist
[[1]]
x y
1 1 a
2 2 b
3 3 c
[[2]]
x y
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
new1 <- dplyr::left_join(filelist[[1]], df3, by = "y")
new2 <- dplyr::left_join(filelist[[2]], df3, by = "y")
newlist <-(new1,new2)
> newlist
[[1]]
x y animal geno
1 1 a snake aa
2 2 b snake ab
3 3 c snake ac
[[2]]
x y animal geno
1 1 a snake aa
2 2 b snake ab
3 3 c snake ac
4 4 d snake aa
5 5 e snake ac
做到这一点的最佳方法是不从原始列表中取出每个数据框,添加新数据,然后创建一个新列表?
答案 0 :(得分:0)
我会使用map
包中的purrr
函数,它像dplyr
一样是tidyverse的一部分:
library(tidyverse)
library(purrr) # loaded when you call tidyverse, but doing it explicitly here
map(filelist, left_join, df3)
[[1]]
x y animal geno
1 1 a snake aa
2 2 b snake ab
3 3 c snake ac
[[2]]
x y animal geno
1 1 a snake aa
2 2 b snake ab
3 3 c snake ac
4 4 d snake aa
5 5 e snake ac
Warning messages:
1: Column `y` joining factors with different levels, coercing to character vector
2: Column `y` joining factors with different levels, coercing to character vector
答案 1 :(得分:0)
如警告消息中所述,因素具有不同的水平。
您可以按照dplyr
的方式将每个数据帧的因子转换为字符:
df %>% mutate_if(is.factor, as.character) -> df
或均化变量y的因子水平:
for (i in 1:length(filelist)) {
x = factor(unique(c(levels(filelist[[i]]$y),levels(df3$y))))
levels(filelist[[i]]$y) = x
levels(df3$y) = x
filelist[[i]] = dplyr::left_join(filelist[[i]], df3, by = "y")
}