I have this nested data
我想取消嵌套它,但我必須在取消嵌套之前標準化列的類
`library(tidyverse`)
nested_data<-iris %>% nest(data = !Species)
#I added to the third dataset an additionnal variable
nested_data$data[[3]]$randomVar<-round(rnorm(nrow(
nested_data$data[[3]]),100,5),1)
#I dropped a column of the second dataset
nested_data$data[[2]]$Sepal.Length<-NULL
#I changed the type of certain variables
nested_data$data[[2]]$Petal.Length<- as.character(
nested_data$data[[2]]$Petal.Length)
nested_data$data[[1]]$Petal.Width<-as.character(
nested_data$data[[1]]$Petal.Width
)
對于某些變數使用不同型別的類,我不能取消嵌套
nested_data%>%unnest(data)
我有這個錯誤資訊:
Error: Can't combine `..1$Petal.Length` <double> and `..2$Petal.Length` <character>.
Run `rlang::last_error()` to see where the error occurred.
我想使用 a或任何方法character
在一行代碼中更改三個資料集中每個資料集的所有變數。for loop
vectorization
我不知道該怎么做。
uj5u.com熱心網友回復:
如果不小心列型別不同,那么可以type.convert
在unnest
library(dplyr)
library(tidyr)
library(purrr)
nested_data %>%
mutate(data = type.convert(data, as.is = TRUE)) %>%
unnest(data)
-輸出
# A tibble: 150 × 6
Species Sepal.Length Sepal.Width Petal.Length Petal.Width randomVar
<fct> <dbl> <dbl> <dbl> <dbl> <dbl>
1 setosa 5.1 3.5 1.4 0.2 NA
2 setosa 4.9 3 1.4 0.2 NA
3 setosa 4.7 3.2 1.3 0.2 NA
4 setosa 4.6 3.1 1.5 0.2 NA
5 setosa 5 3.6 1.4 0.2 NA
6 setosa 5.4 3.9 1.7 0.4 NA
7 setosa 4.6 3.4 1.4 0.3 NA
8 setosa 5 3.4 1.5 0.2 NA
9 setosa 4.4 2.9 1.4 0.2 NA
10 setosa 4.9 3.1 1.5 0.1 NA
# … with 140 more rows
或者如果type.convert
不起作用(由于字符元素,則強制列為 type character
,unnest
然后使用更改列型別type.convert
nested_data %>%
mutate(data = map(data,~
.x %>%
mutate(across(everything(), as.character)))) %>%
unnest(data) %>%
type.convert(as.is = TRUE)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468171.html
上一篇:遍歷嵌套字典-Python
下一篇:如何在python中退出這個回圈