23

在 R 中转置 data.frame 并将其中一列设置为新转置表的标题的最佳方法是什么?我在下面编写了一种方法来做到这一点。由于我还是 R 的新手。我想要改进我的代码的建议以及更像 R 的替代方案。不幸的是,我的解决方案也有点硬编码(即新的列标题位于某个位置)。

# Assume a data.frame called fooData
# Assume the column is the first column before transposing

# Transpose table
fooData.T <- t(fooData)

# Set the column headings
colnames(fooData.T) <- test[1,]

# Get rid of the column heading row
fooData.T <- fooData.T[2:nrow(fooData.T), ]

#fooData.T now contains a transposed table with the first column as headings
4

7 回答 7

26

好吧,您可以通过使用分两步完成

# Transpose table YOU WANT
fooData.T <- t(fooData[,2:ncol(fooData)])

# Set the column headings from the first column in the original table
colnames(fooData.T) <- fooData[,1] 

结果是您可能知道的矩阵,这是由于转置时的类问题。鉴于转置步骤中缺乏命名能力,我认为不会有单行方式来做到这一点。

于 2011-07-11T03:51:36.877 回答
1

这是我的两分钱dplyr,用于data.frame具有分组列和id列的 a。

id_transpose <- function(df, id){
  df %>% 
    ungroup() %>% 
    select(where(is.numeric)) %>% 
    t() %>% 
    as_tibble() %>% 
    setNames(., df %>% pull({{id}}))
}
于 2021-01-07T14:55:51.507 回答
1

你甚至可以在一行中做到这一点:

fooData.T <- setNames(data.frame(t(fooData[,-1])), fooData[,1])

已经有了很好的答案。但是,这个答案可能对那些喜欢简洁代码的人有用。

于 2021-06-28T23:38:08.457 回答
0

使用transposefrom data.table,假设您要在转置后用作标题的列是变量group

fooData.transpose = fooData %>% transpose (make.name = "group")

此外,如果要为转置的列名指定名称,请使用参数keep.names

fooData.transpose = fooData %>% transpose (make.name = "group", keep.names = "column_name")
于 2021-10-05T19:21:20.393 回答
0

这是从这里tiyderse/dplyr采取的另一种方法。

mtcars %>%
  tibble::rownames_to_column() %>%  
  tidyr::pivot_longer(-rowname) %>% 
  tidyr::pivot_wider(names_from=rowname, values_from=value)
于 2021-06-29T13:54:14.977 回答
0

rotate_df现在有一个专用功能可以从sjmisc包中转置数据帧。如果所需的名称在原始 df 的第一列中,则可以通过参数在一行中实现这一点cn

这是一个示例数据框:

df <- data.frame(name = c("Mary", "John", "Louise"), class = c("A", "A", "B"), score = c(40, 75, 80))

df
#    name class score
#1   Mary     A    40
#2   John     A    75
#3 Louise     B    80

执行功能cn = T

rotate_df(df, cn = T)

#      Mary John Louise
#class    A    A      B
#score   40   75     80
于 2022-01-12T14:16:10.090 回答
-1

我有一个类似的问题——我有一个长格式的因子变量,我希望每个因子都是一个新的列标题;使用统计库中的“unstack”一步完成。如果您想要作为标题的列不是一个因素,那么 reshape 库中的“cast”可能会起作用。

于 2012-08-22T14:07:36.263 回答