重塑数据框?
Reshaping Dataframe?
我有一个看起来像这样的数据框:
X1 variables data
2.6 X2 2.5
X3 2.9
我怎样才能将它重塑成这样:
variables data
X1 2.6
X2 2.5
X3 2.9
谢谢!
您可以使用 data.table
中的 melt
library(data.table)#v1.9.5+
melt(setDT(df1), id.var='variables', na.rm=TRUE, value.name='data')[
variable!='data', variables:= variable][,variable:=NULL][]
# variables data
#1: X1 2.6
#2: X2 2.5
#3: X3 2.9
数据
df1 <- structure(list(X1 = c(2.6, NA), variables = c("X2", "X3"),
data = c(2.5,
2.9)), .Names = c("X1", "variables", "data"), class = "data.frame",
row.names = c(NA, -2L))
first_row <- c(names(df1)[1], (df1[, 1][1]))
df1 <- df1[, 2:3 ]
df2 <- rbind(first_row, df1)
df2
# variables data
# X1 2.6
# X2 2.5
# X3 2.9
我有一个看起来像这样的数据框:
X1 variables data
2.6 X2 2.5
X3 2.9
我怎样才能将它重塑成这样:
variables data
X1 2.6
X2 2.5
X3 2.9
谢谢!
您可以使用 data.table
melt
library(data.table)#v1.9.5+
melt(setDT(df1), id.var='variables', na.rm=TRUE, value.name='data')[
variable!='data', variables:= variable][,variable:=NULL][]
# variables data
#1: X1 2.6
#2: X2 2.5
#3: X3 2.9
数据
df1 <- structure(list(X1 = c(2.6, NA), variables = c("X2", "X3"),
data = c(2.5,
2.9)), .Names = c("X1", "variables", "data"), class = "data.frame",
row.names = c(NA, -2L))
first_row <- c(names(df1)[1], (df1[, 1][1]))
df1 <- df1[, 2:3 ]
df2 <- rbind(first_row, df1)
df2
# variables data
# X1 2.6
# X2 2.5
# X3 2.9