简体   繁体   English

通过替换 R 中的单元格复制行

[英]Copy rows by replacing cells in R

I am very new to R, and let me explain the problem.我对 R 很陌生,让我解释一下这个问题。 I have the following data.frame:我有以下 data.frame:

df1<-data.frame(name = c("Ann", "Beth", "Jon", "Mark"),
test1 = c(1,3,2,3),
test2 = c("B",NA,"C",NA)
)

Simply speaking, there are four people.简单的说,有四个人。 Two of them took only test1 and have results for that test.他们中的两个只参加了 test1 并获得了该测试的结果。 The other two took both tests.另外两人参加了两项考试。 I wish to transform this data.frame into the following:我希望将此 data.frame 转换为以下内容:

df2<-data.frame(name = c("Ann", "Ann", "Beth", "Jon", "Jon", "Mark"),
test1 = c(1,"B",3,2,"C",3)
)

In other words, I wish to have all test results in one column.换句话说,我希望将所有测试结果放在一列中。 The order does not matter in sense that, for example, "second Ann" can be in the last row than in the second row.顺序无关紧要,例如,“第二个安”可以在最后一行而不是在第二行。 Since Ann and Jon took two tests, I (i) created an additional row for both of them, (ii) copied their test2 results into test1, and (iii) deleted test2 column.由于 Ann 和 Jon 进行了两次测试,我 (i) 为他们创建了一个额外的行,(ii) 将他们的 test2 结果复制到 test1 中,以及 (iii) 删除了 test2 列。

My attempt.我的尝试。 I first duplicated rows which have nonempty values in test2:我首先复制了 test2 中具有非空值的行:

df1 <- bind_rows(df1, 
              df1 %>%
                filter_at(vars(starts_with("test2")), all_vars(!is.na(.))))

Now I cannot wrap my head around how to transfer test2 results in new rows into test1.现在我无法解决如何将新行中的 test2 结果传输到 test1 的问题。

Does this work:这是否有效:

df1 %>% mutate(test1 = as.character(test1)) %>% pivot_longer(!name, names_to = 'test') %>% select(-2) %>% na.omit()
# A tibble: 6 x 2
  name  value
  <chr> <chr>
1 Ann   1    
2 Ann   B    
3 Beth  3    
4 Jon   2    
5 Jon   C    
6 Mark  3    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM