根据条件合并两个列表列

时间:2020-07-14 14:54:55

标签: r

我有如下数据:

---
title: "Radar"
output:
  html_document:
---

```{r radarchart, echo=FALSE, fig.cap='two plots', fig.subcap= c('A figure', 'A table'), out.width = '.49\\linewidth', echo = F, fig.align='center'}
library(gridExtra)
library(grid)



score_selected = as.data.frame(t(c(1,3,4,5,1,2,2,1,3,4)))

data <- rbind(rep(5,10) , rep(0,10) , score_selected)

radarchart(data[c(1,10,9,8,7,6,5,4,3,2)], axistype=0, seg = 5, cglwd = 0.5, cex.main = 0.8,
             pfcol=rgb(0.2,0.5,0.5,0.5), cglcol="grey",
             cglty=1, vlcex=0.8)
             
grid.newpage()
grid.table(head(mtcars[,1:6]), theme = ttheme_minimal())
      
```

它有两列,其中包含列表。我想将两列合并为一个列。

首先,我只想保留 extractedNames1 extractedNames2 1 2 synopsys 3 4 somero 5 cbiz medical management professionals, cbiz, cbiz, cbiz, cbiz, cbiz 6 7 8 johnson, johnson, johnson 9 iridium 10 skillsoft, skillsoft, skillsoft skillsoft, skillsoft, skillsoft 值。因此uniquecbiz medical management professionals列中将是唯一值,但是extractedNames1将在cbiz, cbiz, cbiz, cbiz, cbiz列中折叠为cbiz

第二,我想根据条件进行合并。如果extractedNames2中没有结果,则取extractedNames1中的unique值。如果两列都存在结果,则仅保留extractedNames2中的结果。 (因此,我只想合并两列,但前提是extractedNames1列中有空白。)

预期输出:

extractedNamesFina

extractedNames1

数据

l
1
2   synopsys
3
4   somero
5   cbiz medical management professions,
6
7
8   Johnson
9   iridium
10  skillsoft

2 个答案:

答案 0 :(得分:2)

您可以在map()中使用purrr系列。

library(purrr)
df2 <- as.data.frame(matrix(nrow = nrow(df)))
df2[[1]] <- pmap(map(df, map, unique), ~ if(length(.x)) .x else .y)
df2

#                                         V1
# 1                                         
# 2                                 synopsys
# 3                                         
# 4                                   somero
# 5   cbiz medical management professionals,
# 6                                         
# 7                                         
# 8                                  johnson
# 9                                  iridium
# 10                               skillsoft

如果要将列表插入data.frame中,则需要创建一个与列表相同长度的data.frame。一种更方便的方法是使用tibble(),它可以将列表作为输入。

library(tibble)
tibble(new = pmap(map(df, map, unique), ~ if(length(.x)) .x else .y))

# # A tibble: 10 x 1
#    new      
#    <list>   
#  1 <chr [0]>
#  2 <chr [1]>
#  3 <chr [0]>
#  4 <chr [1]>
#  5 <chr [1]>
#  6 <chr [0]>
#  7 <chr [0]>
#  8 <chr [1]>
#  9 <chr [1]>
# 10 <chr [1]>

as_tibble_col(pmap(map(df, map, unique), ~ if(length(.x)) .x else .y), column_name = "new")

答案 1 :(得分:0)

您可以尝试以下方法:

.vscode

结果:

args