r - 如何在数据框的一行中将字符串与向量的每个元素连接起来?
问题描述
原谅我的格式;这是我的第一个问题。
我有一个数据框,其中一个变量是字符串,另一个变量是向量。
我想做的是将字符串连接到数据框每一行中向量的每个元素。字符串不一定都是相同的长度。这些向量不一定都是相同的长度。
基本上,我试图从这里得到:
数据框:作业
用户 | 任务 |
---|---|
'Bill' |
c(1, 2, 3) |
'Jae' |
c(2, 5, 6, 7, 8, 9, 10) |
'Marsha' |
c(1, 11) |
'Sunil' |
c(1, 4, 11, 12) |
到这里:
用户任务 |
---|
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
连接用户和任务之类的方法,但我认为最终结果如下:
用户任务 |
---|
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
选项有些摸索,但我仍然太新,无法真正理解如何使用它。
解决方案
使用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))