簡體   English   中英

在R中將數據集從行轉換為列

[英]transforming a dataset from rows to columns in R

我想將數據集的行轉換為列。

selection  weight
sel1       0.4
sel2       0.5



selection_1   weight_1    selection_2   weight_2
sel1          0.4         sel2          0.6

我嘗試重塑形狀,但不確定使用什么參數。

是否可以使用基本R函數進行此轉換?

據我所知,我認為您首先需要創建一個timevaridvar才能使用reshape (即使idvar在這里是一個常量。)

df1_wide <- reshape(data = transform(df1,
                                     timevar = seq_len(nrow(df1)),
                                     idvar = 1L),
                    timevar = "timevar",
                    idvar = "idvar",
                    direction = "wide",
                    sep = "_")
df1_wide
#  idvar selection_1 weight_1 selection_2 weight_2
#1     1        sel1      0.4        sel2      0.5

您可以通過以下方式取消選擇idvar

cols_to_keep <- setdiff(names(df1_wide), "idvar")
df1_wide[cols_to_keep]

這很麻煩,但是有效。

對於示例,我將構建您描述的數據框:

selection <- c('sel1','sel2')
weight <- c(0.4,0.5)
df <- data.frame(selection = selection,weight = weight)

首先,請確保selection變量是character類型,而不是factor

df$selection <- as.character(df$selection)

為了創建新數據框的名稱列表,我們創建正確的字符串並將其粘貼到索引中。

indices <- sort(c(1:nrow(df),1:nrow(df)))
tags <- c(rbind(rep(names(df)[1],nrow(df)),rep(names(df)[2],nrow(df))))
new_names <- sapply(1:(2*nrow(df)),function(j) paste(tags[j],indices[j],sep="_"))

這是作為功能編寫的糊塗部分。 讓我們一步一步地將新變量添加到一個空的數據框中。

make_new_df <- function(df) { 
  new_df <- data.frame()
  for (i in (1:length(new_names))) {
    test <- i %% ncol(df)
    if (test == 0) {
      row_index <- floor(i/ncol(df))
      col_index <- ncol(df)
    } else {
      row_index <- floor(i/ncol(df))+1
      col_index <- (i %% ncol(df))
    }
    new_df[1,new_names[i]] <- df[row_index,col_index]
  }
  return(new_df)
}

讓我們檢查一下它是否適用於您的示例:

> make_new_df(df)
  selection_1 weight_1 selection_2 weight_2
1        sel1      0.4        sel2      0.5

函數make_new_df將適用於具有任意行和列數的輸入數據幀df ,但是它需要正確配置new_names 初步代碼構建new_names將可用於任意數量的行,但僅適用於兩列(因此它在函數外部)。 例如,代碼

selection <- c('sel1','sel2','sel3','sel4')
weight <- c(0.4,0.5,0.6,0.7)
df <- data.frame(selection = selection,weight = weight)
indices <- sort(c(1:nrow(df),1:nrow(df)))
tags <- c(rbind(rep(names(df)[1],nrow(df)),rep(names(df)[2],nrow(df))))
new_names <- sapply(1:(2*nrow(df)),function(j) paste(tags[j],indices[j],sep="_"))
make_new_df(df)

產生

  selection_1 weight_1 selection_2 weight_2 selection_3 weight_3 selection_4 weight_4
1        sel1      0.4        sel2      0.5        sel3      0.6        sel4      0.7

暫無
暫無

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

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