2016-03-13 70 views
1

我有一個看起來像長廣R中去除NA的

Dput樣本數據:

structure(list(variable = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 
1L, 2L, 3L), .Label = c("firstname", "lastname", "title"), class = "factor"), 
    value = structure(c(6L, 2L, 5L, 1L, 3L, 5L, 7L, 8L, 4L), .Label = c("adam", 
    "dingler", "jhon", "miss", "mr", "naji", "stephanie", "williams" 
    ), class = "factor")), .Names = c("variable", "value"), class = "data.frame", row.names = c(NA, 
-9L)) 

我想,這樣它看起來像這個轉換爲寬幅:

enter image description here

我試圖

library(tidyr) final_data <- spread(sample, key = variable, value = value) 但是我在需要的格式獲得輸出不,我得到的輸出格式爲:

enter image description here

我需要幫助,如何擺脫娜的和重組的需要的格式輸出。

+0

他們總是接二連三原始列表? –

+1

'矩陣(樣本$值,3,byrow = TRUE)' – rawr

+0

嗨@rawr我從來沒有想到這一點,感謝這個直觀的解決方案。 – PSraj

回答

2

我們需要創建變量

library(dplyr) 
library(tidyr) 
sample %>% 
    group_by(variable) %>% 
    mutate(n = row_number()) %>% 
    spread(variable, value) %>% 
    select(-n) 
# firstname lastname title 
#  (fctr) (fctr) (fctr) 
#1  naji dingler  mr 
#2  adam  jhon  mr 
#3 stephanie williams miss 
0

序列你可以做到以下幾點:

data <- structure(list(variable = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 
             1L, 2L, 3L), .Label = c("firstname", "lastname", "title"), class = "factor"), 
       value = structure(c(6L, 2L, 5L, 1L, 3L, 5L, 7L, 8L, 4L), .Label = c("adam", 
                        "dingler", "jhon", "miss", "mr", "naji", "stephanie", "williams" 
       ), class = "factor")), .Names = c("variable", "value"), class = "data.frame", row.names = c(NA, 


firstname <- data$value[which(data$variable == "firstname")] 
lastname <- data$value[which(data$variable == "lastname")] 
title <- data$value[which(data$variable == "title")] 

data_new <- data.frame(firstname, lastname, title) 
data_new