如何通过R中的特定列转置数据帧

How to transpose dataframe by specific column in R

我正在为我的硕士论文整理一些数据,并且正在努力重组数据框架。

我有一个看起来像这样的数据框table, with three variables

基本上,我想将它翻转到一边,这样 Sample 就会沿着顶部,下面有两行用于农场和年份。到目前为止,我已经尝试过这些方法(数据框称为 labnums):

labnums <- labnums %>%
  spread(sample, farm + year)

labnums <- xtabs(year + farm~sample, labnums)

但是都不起作用。有谁知道我如何让它发挥作用? (也很抱歉不得不使用图片,我以前从未在这里发布过)

谢谢!

如果你能展示一个例子,结果应该是什么样子,那就太好了。我现在最好的猜测是:

library(dplyr)

df <- data.frame(farm = c(3, 5, 5, 5), 
                 year = c(2017, 2018, 2017, 2017),
                 sample = c(116, 24, 88, 105))

t(df) 
#>        [,1] [,2] [,3] [,4]
#> farm      3    5    5    5
#> year   2017 2018 2017 2017
#> sample  116   24   88  105

df %>% t() %>% as.data.frame()
#>          V1   V2   V3   V4
#> farm      3    5    5    5
#> year   2017 2018 2017 2017
#> sample  116   24   88  105

是你想要的吗?

df <- data.frame(farm=c("BADU003","BADU005"),
                 year= 2017:2018,
                 sample= c("Ralcyone.116","Ralcyone.24"),stringsAsFactors = F)

# transpose matrix
df <- as.data.frame(t(df),stringsAsFactors = FALSE)

# set the names as the values of the 3rd row
df <- setNames(df,df[3,])

# remove 3rd row
df <- df[-3,]

#      Ralcyone.116 Ralcyone.24
# farm      BADU003     BADU005
# year         2017        2018

tidyverse:

library(tidyverse)
gather(df,key,value,-sample) %>% spread(sample,value) %>% column_to_rownames("key")
#      Ralcyone.116 Ralcyone.24
# farm      BADU003     BADU005
# year         2017        2018