如何根据另一个的级别在列上粘贴字符串向量?

时间:2017-09-09 21:00:07

标签: r dataframe split lapply

我试图根据因素的级别对一系列受访者名称应用唯一身份。我使用lapply(paste0)但没有取得任何进展。

library(dplyr)
q46 <- data_frame(
  coop=sample(c('fish','dairy','legumes'),20,replace=T),
  name=sample(c('Leader','President','Agronomist'),20,replace = T)
)
y <- c('.f','.d','.l')
coop_split <- split(q46, q46$coop)

lapply(split(q46,q46$coop), function(x) {
  paste0(q46$name,y[i])})

所需的输出如下:

 name

 Leader.f

 President.f

 Leader.d

我没有坚持这种做法;是否有一个自动执行此操作的功能?

感谢。

1 个答案:

答案 0 :(得分:1)

为什么不使用case_when或ifelse?

library(tidyverse)
q46 %>% 
    mutate(name2 = case_when(coop=='legumes' ~paste0(name, ".l"),
                             coop=='fish' ~paste0(name,".f"),
                             coop=='dairy' ~paste0(name, ".d")))

# A tibble: 20 x 3
  coop       name        name2
 <chr>      <chr>        <chr>
 1 legumes     Leader     Leader.l
 2    fish     Leader     Leader.f
 3 legumes  President  President.l
 4 legumes  President  President.l
 5   dairy     Leader     Leader.d
 6 legumes Agronomist Agronomist.l
 7 legumes  President  President.l
 8    fish Agronomist Agronomist.f
 9    fish     Leader     Leader.f
10 legumes     Leader     Leader.l
11 legumes Agronomist Agronomist.l
12 legumes Agronomist Agronomist.l
13 legumes  President  President.l
14    fish Agronomist Agronomist.f
15   dairy     Leader     Leader.d
16   dairy  President  President.d
17 legumes Agronomist Agronomist.l
18 legumes  President  President.l
19 legumes     Leader     Leader.l
20 legumes Agronomist Agronomist.l