gpt4 book ai didi

r - 连接避免 NA 以生成多行变量

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

假数据

Fruit <- c("Tomato", "Banana", "Kiwi", "Pear")
Colour <- c("Red", "Yellow", NA, "Green")
Weight <- c(10, 12, 6, 8)

dd <- data.frame(Fruit, Colour, Weight)

尝试失败
dd <- dd %>%
mutate(Description = sprintf("%s: %s \n%s: %s \n%s: %s",
names(dd)[1], Fruit,
names(dd)[2], Colour,
names(dd)[3], Weight))

dd$Description[1]

所需的输出:忽略 NA 的多行“描述”变量。

番茄的“描述”变量:
Fruit: Tomato
Colour: Red
Weight: 10

Kiwi, NA 的“描述”变量被忽略!
Fruit: Kiwi
Weight: 6

最佳答案

循环遍历行,删除 NA,然后粘贴:

dd$Description <- unlist(
apply(dd, 1, function(i) {
x <- na.omit(i)
paste(paste0(names(x),":", x), collapse = "\n")
}))

dd
# Fruit Colour Weight Description
# 1 Tomato Red 10 Fruit:Tomato\nColour:Red\nWeight:10
# 2 Banana Yellow 12 Fruit:Banana\nColour:Yellow\nWeight:12
# 3 Kiwi <NA> 6 Fruit:Kiwi\nWeight: 6
# 4 Pear Green 8 Fruit:Pear\nColour:Green\nWeight: 8

关于r - 连接避免 NA 以生成多行变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50372181/

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