Home > other >  How to transpose only one row of a dataframe in R
How to transpose only one row of a dataframe in R

Time:01-16

enter image description here

I want the accuracy row to be in the column part

CodePudding user response:

Here a step by step manual solution with base R

Code

#Data
df <-
  data.frame(X = c(1:3,"accurracy"), precision = runif(4), recall = runif(4), f1.score = runif(4))

#Save the last row data in a vector
accurracy <- unlist(df[nrow(df),])

#Eliminate the last row from the original data.frame
df <- df[-nrow(df),]

#Create a new column
df$"accurracy" <- accurracy[-1]

df

Output

  X precision    recall  f1.score          accurracy
1 1 0.6075635 0.4839641 0.3071190   0.12418847065419
2 2 0.5337823 0.3673568 0.8207251  0.951568570220843
3 3 0.2854789 0.7080209 0.8552161 0.0459401197731495

CodePudding user response:

An option by first filter the accuracy column and convert to longer format and add that back with bind_cols to the dataframe with the specific row like this:

library(dplyr)
library(tidyr)
df %>% 
  filter(X == "accuracy") %>% 
  pivot_longer(-X, values_to = "accuracy") %>%
  select(accuracy) %>%
  bind_cols((df %>% filter(X != 'accuracy')), .)
#>   X precision recall f1.score accuracy
#> 1 1     1.000  0.857    0.923     0.94
#> 2 2     0.875  1.000    0.930     0.94
#> 3 3     1.000  1.000    1.000     0.94

Created on 2023-01-15 with reprex v2.0.2

CodePudding user response:

Please try

library(tidyverse)

df$accuracy <- df[X=='accuracy']
  • Related