簡體   English   中英

R - 將 dataframe 拆分為列表,同時保留第二列,然后按列名重命名列表元素

[英]R - split dataframe into list by column while retaining a second column, then rename list elements by col name

兩個分開的問題。 第一部分看起來很簡單,但我一定錯過了。 我想按列拆分 dataframe,但是,在這些數據中,在每個列表元素中保留state列。

然后理想情況下,我想將列表元素重命名為列名並標准化列表元素中的列名。

更容易顯示:

df <- data.frame(state = rep(letters[1:3], each = 2),
                 score1 = rnorm(6, 1, 1),
                 score2 = rnorm(6, 10, 1))

我最想得到的是

$`score1`
   state      value 
1      a  0.3406192
2      a  0.9598098
3      b  0.8813060
4      b  0.9803431
5      c  0.5143215
6      c -0.4401475 

$`score2`
   state      value
1      a  10.332035
2      a  11.572288
3      b  8.930529
4      b  10.916287
5      c  9.405007
6      c  12.181647

這個 SO 帖子非常接近,但我認為可能有更好的方法來保留一個state列,同時拆分其他列。

最終目標是通過 state 將這些嵌套到一個 tibble 中,通過 state 對每個進行匯總以獲得平均值和 sd,然后使用purrr::map()在每個模型上運行一系列模型(因此列名標准化)。 如果有人想出一些東西,一個 tidyverse 建議會很棒,但其他解決方案也很酷。

獲取長格式的 dataframe 並使用split

library(tidyverse)

df %>%
  pivot_longer(cols = starts_with('score')) %>%
  split(.$name) %>%
  map(~.x %>% select(-name))

#$score1
# A tibble: 6 x 2
#  state  value
#  <chr>  <dbl>
#1 a      1.58 
#2 a      0.567
#3 b     -0.313
#4 b      0.756
#5 c      0.236
#6 c      1.05 

#$score2
# A tibble: 6 x 2
#  state value
#  <chr> <dbl>
#1 a      9.93
#2 a      9.96
#3 b     12.2 
#4 b      9.41
#5 c      9.40
#6 c      9.97

您也可以使用group_split並避免map步驟,但它不會在 output 中給出列表名稱( score1score2 )。

df %>%
  pivot_longer(cols = starts_with('score')) %>%
  group_split(name, .keep  = FALSE)

基礎 R 解決方案:

 # Reshape the data.frame to long format: long_df => data.frame
long_df <- reshape(
  df,
  direction = "long",
  varying = which(names(df) != "state"),
  idvar = "state",
  v.names = "value",
  timevar = "score_no",
  times = names(df)[names(df) != "state"],
  new.row.names = seq_len((sum(names(df) != "state") * nrow(df)))
)
# Allocate some memory: df_list => empty list: 
df_list <- vector("list", length(unique(long_df$score_no)))

# Split the data.frame into a list: df_list => list of data.frames
df_list <- split(long_df[,names(long_df) != "score_no"], long_df$score_no)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM