2017-10-22 144 views
0

我想將具有n行和n列的數據幀轉換爲單行,並添加了列名和行名稱將R中的錶轉換爲單行

例如,我想將下表轉換爲單行

Country   Percentage 
    United States 97.89% 
    United Kingdom 0.65% 
    Switzerland  0.50% 
    Ireland   0.48% 
    Singapore  0.45% 
    Hong Kong  0.03% 

像這樣

Country_United States_Percentage Country_United Kingdom_Percentage 
97.89%          0.65% 

等等

+0

'dplyr :: spread()'?可能會幫助 –

回答

0

這個Wi會讓你非常接近:

library(tidyverse) 
df <- tribble(
    ~Country, ~Percentage, 
    "United States", 97.89, 
    "United Kingdom", 0.65, 
    "Switzerland", 0.5, 
    "Ireland", 0.48, 
    "Singapore", 0.45, 
    "Hong Kong", 0.03 
) 

spread(df, Country, Percentage, sep='_') 
+0

謝謝,這非常有用 –