gpt4 book ai didi

r - 如何在 R 中将一个字符串列与多个字符串列连接起来

转载 作者:行者123 更新时间:2023-12-05 03:17:19 24 4
gpt4 key购买 nike

我正在尝试按行连接数据框 (df1) 中的值,并获得 (df2) 的结果。

# Input
df1 <- data.frame (first_column = c("A", "B", "C", "D"),
second_column = c("var1", "var2", "var3", "var4"),
third_column = c("var5", "var6", "var7", " "),
fourth_column = c("var8", "var9", " ", " "))
# Ouput
df2 <- data.frame (first_column = c("A var1", "B var2", "B var3", "B var4"),
second_column = c("A var5", "B var6", "B var7", "B "),
thrid_column = c("A var8", "B var9", "B ", "B "))

到目前为止,我最好的结果是使用以下代码,但不是我想要的:

# Get the number of columns as df1 will differ in size from time to time,
and the only thing I'd like to change to the script is the file path for df1.

nc <- ncol(df1)

df2 <- data.frame(paste(df1$first_column, df1[,c(2:nc)]))

任何 💭 想法和反馈将不胜感激。 😁

最佳答案

我们可以循环跨越从'second_column'到最后的列,粘贴(str_c)带有列值的first_column并重命名

library(dplyr)
library(stringr)
df1 %>%
transmute(across(second_column:last_col(),
~ str_c(first_column, .x, sep = ' '))) %>%
rename_with(~ names(df1)[-length(.x)])

-或使用base R

df2 <- df1
df2[-ncol(df1)] <- lapply(df1[-1], \(x) paste(df1$first_column, x))
df2 <- df2[-ncol(df2)]

关于r - 如何在 R 中将一个字符串列与多个字符串列连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74173488/

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