我无法在数据框中提取列表名称。
我的嵌套列表如下:
library(tidyverse)
library(dplyr)
library(purrr)
category <- list(fruits<-c("apples","orange", "pear","banana","strawberries"),
vegetables<-c("cauliflower","potato","onion","tomato"),
dairy<-c("goats milk", "cows milk"))
我的数据框:
column1<-c("apples","potato","onion","goats milk")
df<-as.data.frame(column1)
final<-df%>%mutate(listname=column1%in%category)
我得到以下结果:
column1 listname
1 apples FALSE
2 potato FALSE
3 onion FALSE
4 goats milk FALSE
我希望拥有的是:
column1 listname
1 apples fruit
2 potato vegetable
3 onion vegetable
4 goats milk dairy
真的很感谢你的帮助。
谢谢
答案 0 :(得分:6)
merge(df,stack(category),by.x = "column1",by.y= "values")
column1 ind
1 apples fruits
2 goats milk dairy
3 onion vegetables
4 potato vegetables
但首先要确保您拥有如下所示的类别:
category <- list(fruits=c("apples","orange", "pear","banana","strawberries"),
vegetables=c("cauliflower","potato","onion","tomato"),
dairy=c("goats milk", "cows milk"))
您也可以使用:
library(dplyr)
left_join(df,stack(category),c("column1"="values"))