Reputation: 381
i want to rotate a data.frame in R. my dataframe looks like this:
d <- data.frame( A = c("Att1","Att2"), b = c(12,10), c =c(8,9), d =c (1,2))
and in the end my dataframe should looks like following:
d2 <- data.frame( name = c("B","C","D"), Att1 = c(10,8,1), Attr2 = c(10,9,2))
I already tried to use the t()-method, but there is always this error:
Column d
must be a 1d atomic vector or a list
how can i perform the rotate operation on the dataframe? Thanks for any help! regards
Upvotes: 1
Views: 3159
Reputation: 11965
You need to first transpose it and then follow below steps
library(tibble)
df <- data.frame(t(d), stringsAsFactors = F)
colnames(df) <- df[1, ] #assign 1st row to column name
df <- df[-1, ]
df <- rownames_to_column(df, "name") #assign row name to a new column
gives
> df
name Att1 Att2
1 b 12 10
2 c 8 9
3 d 1 2
Sample data:
d <- structure(list(A = structure(1:2, .Label = c("Att1", "Att2"), class = "factor"),
b = c(12, 10), c = c(8, 9), d = c(1, 2)), class = "data.frame", row.names = c(NA,
-2L))
Upvotes: 1