2017-09-27 40 views
0

我想采取一个数据帧像这样以变量名柱而出的和R中

name  response 
1 Phil  Exam 
2 Terry  Test 
3 Simmon  Exam 
4 Brad  Quiz 

,把它变成这个

name  response Exam Test Quiz 
    1 Phil  Exam  Exam 
    2 Terry  Test    Test 
    3 Simmon  Exam  Exam 
    4 Brad  Quiz      Quiz 

创建新列我试图用一个for循环,提取每一行。然后我会检查列是否已经存在,如果没有,它会创建一个新列。我无法接近工作,我不确定如何做到这一点。

+0

基本上是一个模型矩阵 - 'cbind(DAT,model.matrix(〜响应+ 0,数据= DAT))' – thelatemail

回答

2

这可以通过几种方法完成。可能是一个很好的机会,结识了tidyverse:

library(tidyverse) 
new.df <- spread(old.df, response, response) 

这是一个不寻常的使用tidyr::spread()。在这种情况下,它会根据“响应”中的值构造新的列名称,并使用“响应”中的值填充这些列。参数fill可用于更改生成的空白单元格中的内容。

+0

我在我的方式来发布一样。很高兴我刷新了。 –

+0

这工作非常好,谢谢! – rss1080

+0

@ rss1080如果这可行,请接受此帖作为答案。 – www

0

基础R解决方案。我们可以创建一个函数来替换与目标单词不匹配的单词,然后在数据框中创建新列。

# Create example data frame 
dt <- read.table(text = " name  response 
1 Phil  Exam 
2 Terry  Test 
3 Simmon  Exam 
4 Brad  Quiz", 
       header = TRUE, stringsAsFactors = FALSE) 

# A function to create a new column based on the word in response 
create_Col <- function(word, df, fill = NA){ 
    new <- df$response 
    new[!new == word] <- fill 
    return(new) 
} 

# Apply this function 
for (i in unique(dt$response)){ 
    dt[[i]] <- create_Col(word = i, df = dt) 
} 

dt 
    name response Exam Test Quiz 
1 Phil  Exam Exam <NA> <NA> 
2 Terry  Test <NA> Test <NA> 
3 Simmon  Exam Exam <NA> <NA> 
4 Brad  Quiz <NA> <NA> Quiz 
0

我们可以使用dcast

library(data.table) 
dcast(setDT(df1), name + response ~ response, value.var = 'response', fill = "") 
#  name response Exam Quiz Test 
#1: Brad  Quiz  Quiz  
#2: Phil  Exam Exam   
#3: Simmon  Exam Exam   
#4: Terry  Test   Test