在列表中堆叠数据框列

时间:2021-03-20 12:35:42

标签: r list dataframe lapply rbind

我有一个包含两个数据框的列表:

dat.list<- list(dat1=data.frame(col1=c(3,4,5),
                                col2=c(5,3,1),
                                col3=c(8,2,5),
                                col4=c(6,7,4)),
                dat2=data.frame(col1=c(2,1,3),
                                col2=c(6,9,2),
                                col3=c(4,2,1),
                                col4=c(9,5,6)))
dat.list
# $dat1
#   col1 col2 col3 col4
# 1    3    5    8    6
# 2    4    3    2    7
# 3    5    1    5    4

# $dat2
#   col1 col2 col3 col4
# 1    2    6    4    9
# 2    1    9    2    5
# 3    3    2    1    6

我正在尝试将列表中两个数据框中的列堆叠起来,以便“col3”低于“col1”而“col4”低于“col2”,如下所示:

# $dat1
#  newcol1 newcol2
# 1       3       5
# 2       4       3
# 3       5       1
# 4       8       6
# 5       2       7
# 6       5       4

# $dat2
#   newcol1 newcol2
# 1       2       6
# 2       1       9
# 3       3       2
# 4       4       9
# 5       2       5
# 6       1       6

我尝试将 this post 的答案调整为 lapply() 函数,如下所示,但我收到错误“类型‘闭包’的对象不是子集化的”。

lapply(dat.list, function(x) transform(x, 
                                       data.frame(grupo1 = unlist(c(.[,"col1"], .[,"col3"])),
                                                   grupo2 = unlist(c(.[,"col2"], .[,"col4"])))))

我还使用 map()pivot_longer() 探索了解决方案,但还没有找到方法。如何获得所需的输出?

1 个答案:

答案 0 :(得分:1)

您可以将 try: sales = Sale.objects.get(id=pk) except Sale.DoesNotExist: return ValidationError(f'No sale by id {pk}') lapplyrbind 一起使用,如下所示:

setNames

退货

cols1 <- c("col1", "col2")
cols2 <- c("col3", "col4")

lapply(dat.list, function(x) rbind(x[, cols1], setnames(x[, cols2], cols1)))

如果没有 #$dat1 # col1 col2 #1 3 5 #2 4 3 #3 5 1 #4 8 6 #5 2 7 #6 5 4 # #$dat2 # col1 col2 #1 2 6 #2 1 9 #3 3 2 #4 4 9 #5 2 5 #6 1 6 ,我们会看到来自 setNames 的以下错误:

<块引用>

match.names(clas, names(xi)) 中的错误: 名称与以前的名称不匹配

所以我们需要一个“Simple way to get rbind to ignore column names”。

相关问题