2016-03-13 61 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