【问题标题】:How can I concatenate a string with each element of a vector within a row of a data frame?如何在数据框的一行中将字符串与向量的每个元素连接起来?
【发布时间】:2021-03-25 06:00:52
【问题描述】:

原谅我的格式;这是我的第一个问题。
我有一个数据框,其中一个变量是字符串,另一个变量是向量。
我想做的是将字符串连接到数据框每一行中向量的每个元素。字符串不一定都是相同的长度。向量不一定都是相同的长度。
基本上,我试图从这里开始:

数据框:分配

user task
'Bill' c(1, 2, 3)
'Jae' c(2, 5, 6, 7, 8, 9, 10)
'Marsha' c(1, 11)
'Sunil' c(1, 4, 11, 12)

到这里:

user-task
c('Bill-1', 'Bill-2', 'Bill-3')
c('Jae-2', 'Jae-5', 'Jae-6', 'Jae-7', 'Jae-8', 'Jae-9', 'Jae-10')
c('Marsha-1', 'Marsha-11')
c('Sunil-1', 'Sunil-4', 'Sunil-11', 'Sunil-12')

我尝试过使用paste0 来连接用户和任务,但我认为结果就是这样:

user-task
Bill c(1, 2, 3)
Jae c(2, 5, 6, 7, 8, 9, 10)
Marsha c(1, 11)
Sunil c(1, 4, 11, 12)

我有它的代码,但我一直对尝试在此框中包含代码感到沮丧。这么多错误!这就像在调试 R 之后,我在调试 StackOverflow。我对 apply 选项有点摸索,但我还是太新,无法真正理解如何使用它。

【问题讨论】:

  • 要插入代码块,您只需在代码块之前和之后的一行中使用三个反引号。要插入内联代码,请单反引号。

标签: r dataframe vector concatenation


【解决方案1】:

不确定您的数据框中是否有“c”函数。但看看这是否有效:

library(dplyr)
library(tidyr)
library(stringr)
df %>% mutate(id = row_number()) %>% mutate(task = str_remove_all(task, '[c\\(||)]')) %>% separate_rows(task) %>% 
group_by(id) %>% transmute(usertask = str_c(user,'-',task, collapse = ',')) %>% ungroup() %>% select(-id) %>% distinct
# A tibble: 4 x 1
  usertask                                  
  <chr>                                     
1 Bill-1,Bill-2,Bill-3                      
2 Jae-2,Jae-5,Jae-6,Jae-7,Jae-8,Jae-9,Jae-10
3 Marsha-1,Marsha-11                        
4 Sunil-1,Sunil-4,Sunil-11,Sunil-12  

【讨论】:

  • 感谢您的回复!我遇到的唯一问题是错误提示 1: Problem with 'mutate()' input 'task'. argument is not an atomic vector; coercing 但输出看起来仍然像我想要的一样。
【解决方案2】:

使用apply 和paste。

apply(d, 1, function(x) paste(x[1], unlist(x[2]), sep="-"))
# [[1]]
# [1] "Bill-1" "Bill-2" "Bill-3"
# 
# [[2]]
# [1] "Jae-2"  "Jae-3"  "Jae-4"  "Jae-5"  "Jae-6"  "Jae-7"  "Jae-8" 
# [8] "Jae-9"  "Jae-10"
# 
# [[3]]
# [1] "Marsha-1"  "Marsha-11"
# 
# [[4]]
# [1] "Sunil-1"  "Sunil-4"  "Sunil-11" "Sunil-12"

或者,使用do.call。

apply(d, 1, function(x) do.call(paste0, c(sapply(x, unlist), "-")[c(1, 3, 2)]))

数据

d <- structure(list(user = c("Bill", "Jae", "Marsha", "Sunil"), task = structure(list(
    1:3, 2:10, c(1, 11), c(1, 4, 11, 12)), class = "AsIs")), class = "data.frame", row.names = c(NA, 
-4L))

【讨论】:

  • 感谢您的回复!仅出于我自己的理解,c(1, 3, 2) 在这种语法中做了什么?那是在其他条目之间加上“-”吗?
  • @Aaron 谢谢你的问题。这是do.call 方法,可能对更大的问题有用,c(c(1, 3, 2) 在apply 生成的行值之间带来"-"。 do.call 调用该函数并需要列表中的其他参数以正确的顺序排列。比较2^3 和do.call("^", list(2, 3)),但这超出了这个问题。实际上,使用标准方法更容易解决您的问题,请参阅更新。
【解决方案3】:

也可以使用 unnest():

d %>%
unnest(cols=c(task)) %>%
mutate(user1 = paste0(user,"-",task)) %>%
group_by(user) %>%
summarise(user_task = paste(user1,collapse=", "))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2015-12-02
    • 2019-12-03
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多