如何解决使用“嵌套”引起列表列列表的问题?

时间:2019-01-23 19:00:00

标签: r dataframe tibble

我正在处理包含一些信息的基本数据帧,此信息用于生成数据列的新列。

我曾尝试使用map2函数,但结果并不理想,使用nest函数和来自purrr包的小标题,结果与我期望的结果更接近。

modelBuilder.Entity<MyModel>().Property(x=>x.Id).HasDefaultValueSql("NEWSEQUENTIALID()");

生成新列时,将其创建为列表列表,而不创建为元素列表。

library(tidyverse)
library(dplyr)
library(purrr)
library(RcppRoll)

dfBase <- data.frame(id = sample(letters[1:3], 3, replace = TRUE),
              dat1 = rnorm(n = 3, 1, 1),
              dat2 = rnorm(n = 3, 2, 1))
View(dfBase)

dfOperations <- function(dat1, dat2){
Sum  = dat1+dat2
Rest = dat1-dat2
Mult = dat1*dat2
Div  = dat1/dat2

test <- tibble(
Opera = c('Sum','Rest','Mult','Div'),
Resul = c(Sum, Rest, Mult, Div))%>%nest()
} 

for (x in 1:nrow(dfBase)) {
dfBase$Result[x] <- dfOperations(dfBase$dat1[x],dfBase$dat2[x])
}


dfBase
str(dfBase)
View(dfBase$Result)

如何删除或消除列表1,仅留下第二个列表Opera and Resul?

1 个答案:

答案 0 :(得分:1)

尝试对每次循环迭代使用dfOperations访问[[1]]的输出:

for (x in 1:nrow(dfBase)) {
dfBase$Result[x] <- dfOperations(dfBase$dat1[x],dfBase$dat2[x])[[1]]
}

'data.frame':   3 obs. of  4 variables:
 $ id    : Factor w/ 3 levels "a","b","c": 1 3 2
 $ dat1  : num  0.849 2.659 0.862
 $ dat2  : num  2.45 1.15 1.35
 $ Result:List of 3
  ..$ :Classes ‘tbl_df’, ‘tbl’ and 'data.frame':        4 obs. of  2 variables:
  .. ..$ Opera: chr  "Sum" "Rest" "Mult" "Div"
  .. ..$ Resul: num  3.301 -1.603 2.082 0.346
  ..$ :Classes ‘tbl_df’, ‘tbl’ and 'data.frame':        4 obs. of  2 variables:
  .. ..$ Opera: chr  "Sum" "Rest" "Mult" "Div"
  .. ..$ Resul: num  3.81 1.51 3.06 2.31
  ..$ :Classes ‘tbl_df’, ‘tbl’ and 'data.frame':        4 obs. of  2 variables:
  .. ..$ Opera: chr  "Sum" "Rest" "Mult" "Div"
  .. ..$ Resul: num  2.208 -0.484 1.16 0.64