gpt4 book ai didi

r - 使用 `glue` 将一列中的变量替换为另一列中的变量

转载 作者:行者123 更新时间:2023-12-04 10:20:32 25 4
gpt4 key购买 nike

如果我有用户的消息列表,我正在尝试保留数据框。我希望能够用我引用的列中的内容替换消息中的变量。

例如,这有效:

df <- data.frame(id = rep(1:3, each = 3),
this = rep(letters[1:3], each = 3),
that = rep(letters[24:26], each = 3),
foo = rep(c("apple", "pear", "banana"), each = 3))

df %>% mutate(message = glue("{this} is {that}"))

但这不会:

library(tidyverse)
library(glue)

verbiage <- data.frame(id = 1:3,
message = c("{this} is {that}", "{foo} is something", "something is {foo}"))

verbiage

df <- data.frame(id = rep(1:3, each = 3),
this = rep(letters[1:3], each = 3),
that = rep(letters[24:26], each = 3),
foo = rep(c("apple", "pear", "banana"), each = 3))

df

df %>%
inner_join(verbiage, by = "id") %>%
mutate(message = glue(message))

最佳答案

我们可以使用 rowwise

library(glue)
library(dplyr)
df %>%
inner_join(verbiage, by = "id") %>%
rowwise %>%
mutate(message = as.character(glue(as.character(message))))
# A tibble: 9 x 5
# Rowwise:
# id this that foo message
# <int> <fct> <fct> <fct> <chr>
#1 1 a x apple a is x
#2 1 a x apple a is x
#3 1 a x apple a is x
#4 2 b y pear pear is something
#5 2 b y pear pear is something
#6 2 b y pear pear is something
#7 3 c z banana something is banana
#8 3 c z banana something is banana
#9 3 c z banana something is banana

关于r - 使用 `glue` 将一列中的变量替换为另一列中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60877134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com