gpt4 book ai didi

跨列滚动粘贴字符串

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

我有这种类型的数据:

df <- data.frame(
w1 = c("A", "B", "C", "E", "F", "G"),
w2 = c("B", "G", "C", "D", "E", "V"),
w3 = c("D", "S", "O", "F", NA, "N"),
w4 = c("E", "U", NA, "T", NA, NA),
w5 = c("C", NA, NA, NA, NA, NA)
)

我需要遍历列对,将单独的字符串滚动粘贴到双字母组中。请注意,在实际数据中,字符串具有可变的字符长度和字符类型。我试过这个但失败了:

df[, paste0("bigr_", 1:4, "_", 2:5)] <- lapply(df[, 1:5], 
function(x) paste(x[i], x[i+1], sep = " "))

预期输出是:

  w1 w2   w3   w4   w5 bigr_1_2 bigr_2_3 bigr_3_4 bigr_4_5
1 A B D E C A B B D D E E C
2 B G S U <NA> B G G S S U <NA>
3 C C O <NA> <NA> C C C O <NA> <NA>
4 E D F T <NA> E D D F F T <NA>
5 F E <NA> <NA> <NA> F E <NA> <NA> <NA>
6 G V N <NA> <NA> G V V N <NA> <NA>

我对 dplyr 解决方案最感兴趣,但我也对其他解决方案持开放态度和感激之情。

最佳答案

正如您所说,您对 dplyr 解决方案最感兴趣,这可以使用 mutate()across() 来实现。如果这没有达到所需的确切输出,您可以更改应用于每一列的函数。

df %>%
mutate(
across(
# For the first four columns (i.e. has number 1-4 in column name)
matches("[1-4]"),

# Apply custom function
function(col) {

# Paste together
paste(
col, # the data in the current column
cur_data()[[which(names(cur_data()) == cur_column())+1]], # and the data in the next column along
sep = " "
)
},
.names = "{gsub(pattern = 'w', replacement = 'bigr_', {col})}" # alter name of new cols (replace 'w' with 'bigr_')
)
) %>%

# EDIT: added to rename columns to match desired output
rename_with(.cols = matches("bigr"),
.fn = function(colname) {
paste0(colname, "_", as.numeric(gsub(pattern = "bigr_", replacement = "", colname))+1)
})

关于跨列滚动粘贴字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72012865/

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