重塑数据帧?

时间:2015-07-17 20:06:53

标签: r dataframe reshape

我的数据框看起来像这样:

private static async Task<string> ID( string wmiClass, string wmiProperty, string wmiMustBeTrue ) {
    Task<string> T = Task.Run( ( ) => {
        Stopwatch SW = new Stopwatch( );
        SW.Start( );
        ManagementObjectCollection.ManagementObjectEnumerator MOE = new ManagementObjectSearcher(
            "SELECT " +
                wmiProperty +
            " FROM "
                + wmiClass +
            ( string.IsNullOrEmpty( wmiMustBeTrue ) ? "" : "WHERE " + wmiMustBeTrue + " = True" ) ).Get( ).GetEnumerator( );
        while ( MOE.MoveNext( ) )
            if ( MOE.Current[wmiProperty] != null && !string.IsNullOrEmpty( MOE.Current[wmiProperty].ToString( ) ) ) {
                SW.Stop( );
                Console.WriteLine( "Querying " + wmiProperty + " of " + wmiClass + " took " + SW.Elapsed.ToString( ) );
                return MOE.Current[wmiProperty].ToString( );
            }
        SW.Stop( );
        Console.WriteLine( "Querying " + wmiProperty + " of " + wmiClass + " took " + SW.Elapsed.ToString( ) + "; returned null." );
        return null;
    });
    await T;
    if ( T.Exception == null )
        return T.Result;
    else {
        Console.WriteLine( "Exception in ID Method Function : wmiClass : " + wmiClass + "; wmiPriperty : " + wmiProperty + ";" );
        Exception E = T.Exception;
        while ( E != null ) {
            Console.WriteLine( E.Message );
            Console.WriteLine( E.StackTrace );
            E = E.InnerException;
        }
        return null;
    }
}

我怎样才能将它改造成这样的东西:

X1     variables   data
2.6    X2          2.5
       X3          2.9

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用melt

中的data.table
  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))

答案 1 :(得分:0)

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