结合R中两列的内容

Combining content of two columns in R

美好的一天

我有以下数据集,基本上用作另一个数据集的键。

代码形式的简短示例部分

Code = c("KBP1369"," "," "," ","KBP1370"," "," ", " "," ")
Description = c("All monetary institutions Credit extended to the domestic ","private sector Total loans and advances","A","J","Monetary aggregates / Money supply: M1(A)", "A","J","M","X")


Data=data.frame(Code,Description) 

我需要以某种方式创建一个列,其中包含描述列下的代码和字母。

所以基本上我需要这些方面的东西。

我只是不知道怎么回事,因为在某些情况下,冗长的描述会超过 1 行,而其他时候只会超过 1 行。最重要的是,字母行数不同,例如 KBP1369 有 4 个字母描述,而 KBP1372 只有 2 个。 我到底该怎么做?

一个想法是将空字符串转换为 NA,fill 并粘贴单个字符串,即

library(dplyr)

Data %>% 
 mutate(Code1 = replace(Code, Code == ' ', NA)) %>% 
 tidyr::fill(Code1) %>% 
 mutate(Code1 = ifelse(nchar(Description) == 1, paste0(Code1, Description), ''))

     Code                                                Description    Code1
1 KBP1369 All monetary institutions Credit extended to the domestic          
2                            private sector Total loans and advances         
3                                                                  A KBP1369A
4                                                                  J KBP1369J
5 KBP1370                  Monetary aggregates / Money supply: M1(A)         
6                                                                  A KBP1370A
7                                                                  J KBP1370J
8                                                                  M KBP1370M
9                                                                  X KBP1370X

要将新结果包含在原始 Code 列中,然后只需在 mutate 中修改它,即

Data %>% 
     mutate(Code1 = replace(Code, Code == ' ', NA)) %>% 
     tidyr::fill(Code1) %>% 
     mutate(Code = ifelse(nchar(Description) == 1, paste0(Code1, Description), Code))