gpt4 book ai didi

r - 逐行连接 data.table 中各列的名称和值

转载 作者:行者123 更新时间:2023-12-05 02:31:01 25 4
gpt4 key购买 nike

类似于this问题,我想连接列值的一个子集。但是,我还想在每个值前面加上列名,用“:”分隔名称和值,并控制用于分隔名称/值对的字符。

例如,这给了我值的串联:

library(data.table)
d <- data.table(x = c(1, 2), y = c(3, 4))

labs_to_get <- c("x", "y")


d[
,
.(x, y, labs = do.call(paste, c(.SD, sep = ", "))),
.SDcols = labs_to_get
]
#> x y labs
#> 1: 1 3 1, 3
#> 2: 2 4 2, 4

但我正在寻找这个:

d[
,
.(x, y, labs = c("x: 1, y: 3", "x: 2, y: 4"))
]
#> x y labs
#> 1: 1 3 x: 1, y: 3
#> 2: 2 4 x: 2, y: 4

reprex package 创建于 2022-04-01 (v2.0.1)

最佳答案

我们可以用Map粘贴相应的名字

d[,
.(x, y, labs = do.call(paste, c(Map(function(u, v)
paste0(v, ": ", u), .SD, labs_to_get), sep = ", "))),
.SDcols = labs_to_get
]

-输出

     x     y       labs
<num> <num> <char>
1: 1 3 x: 1, y: 3
2: 2 4 x: 2, y: 4

或者另一个选项是write.dcf

d[, labs := do.call(paste, 
c(as.list(setdiff(capture.output(write.dcf(.SD)), "")),
sep = ", ")), 1:nrow(d)]
> d
x y labs
<num> <num> <char>
1: 1 3 x: 1, y: 3
2: 2 4 x: 2, y: 4

或者使用apply来遍历行

d[, labs := apply(.SD, 1, \(x) paste(names(x), x, sep = ": ", 
collapse = ", ")), .SDcols = labs_to_get]

或者使用tidyverse

library(dplyr)
library(purrr)
library(stringr)
d %>%
mutate(labs = invoke(str_c, c(across(all_of(labs_to_get),
~str_c(cur_column(), ": ", .x)), sep = ", ")))
x y labs
<num> <num> <char>
1: 1 3 x: 1, y: 3
2: 2 4 x: 2, y: 4

关于r - 逐行连接 data.table 中各列的名称和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71710309/

25 4 0