基于向量和更新列的组值

问题描述 投票:1回答:3

我正在尝试根据预定义的向量对各种值进行分组,然后更新列。

样本数据

df <- data.frame(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

it <- c("Windows", "Windows Server")
animal <- c("Cat", "Dog")
food <- c("Eggs")

我试过但失败了

df$Grouping <- gsub(it, "IT", df$Type)

错误:模式> 1

工作但啰嗦的方法

使用dplyr mutate,我将能够达到我想要的效果,但由于我在向量中有多个元素,所以它很长。

df %>% mutate(Grouping = ifelse(Type == "Windows", "IT", 
                                ifelse ...))

预期输出

ID           Type         Grouping
1  1        Windows          IT
2  2 Windows Server          IT
3  3            Cat        Animal
4  4            Dog        Animal
5  5           Eggs        Food

谢谢!

r dplyr
3个回答
0
投票

一种选择是为映射创建一个list(或data.frame),然后做一个left_join

map <- list(
    it = c("Windows", "Windows Server"),
    animal = c("Cat", "Dog"),
    food = c("Eggs"))

library(dplyr)   
df %>% left_join(stack(map), by = c("Type" = "values"))
#  ID           Type    ind
#1  1        Windows     it
#2  2 Windows Server     it
#3  3            Cat animal
#4  4            Dog animal
#5  5           Eggs   food

1
投票

创建预定义向量的列表,然后检查列表中哪个元素包含df$Type中的项目

mylist = mget(c("animal", "food", "it"))
names(mylist)[max.col(t(sapply(df$Type, function(x) lapply(mylist, function(y) x %in% y))))]
#[1] "it"     "it"     "animal" "animal" "food"

0
投票

发布的问题没有多大意义。具体地说,对于样本数据,存储独立类型向量并不比将类型存储为初始数据帧的属性更简单。也许你可以添加一些颜色,提供有关问题性质的更多细节。

有了这个说,假设您的问题是查找向量存储在不同的源中并需要独立加载,一个简单的循环就足够了。 (我正在使用data.table,因为我甚至不记得如何使用原始data.frame了):

df <- data.table(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))
it <- c("Windows", "Windows Server")
animal <- c("Cat", "Dog")
food <- c("Eggs")

lookup.names <- c("it", "animal", "food")
for (z in 1:length(lookup.names) ) {
    lookup <- get(lookup.names[z]) #maybe need to do some more sophisticated load, like from a file or database
    df[Type %in% lookup, Grouping := lookup.names[z]]
}
© www.soinside.com 2019 - 2024. All rights reserved.