【发布时间】:2021-06-14 01:55:27
【问题描述】:
我有一个 7 列的表,第一列是 id,然后是 3 列蔬菜类型,最后 3 列是水果类型。这些值表明一个人是否有这种蔬菜/水果。有没有办法对蔬菜和水果进行分组,如果这个人有蔬菜/水果,则输出列名?
输入数据框:
id1 <- c("id_1", 1, NA, NA, NA, 1, NA)
id2 <- c("id_2", NA, 1, 1, NA, NA, NA)
input <- data.frame(rbind(id1, id2))
colnames(input) = c("id", "lettuce", "tomato", "bellpeper", "pineapple", "apple", "banana")
预期的输出数据帧:
output_id1 <- c("id_1", "lettuce", "apple")
output_id2 <- c("id_2", "tomato, bellpeper", NA)
output <- data.frame(rbind(output_id1, output_id2))
colnames(output) <- c("id", "veg", "fruit")
【问题讨论】:
-
如果您对返回名称中包含“veg”和“fruit”不感兴趣,您可以从一开始就完全删除这些词吗?比如说,在进行任何分析之前重命名输入数据框。
-
是的,这是可行的。我将编辑问题