R 按字符向量列表筛选数据帧
我试图根据字符向量列表过滤数据帧,并获得每个向量的输出。下面是一个例子来澄清我的问题: 这就是我拥有的数据类型R 按字符向量列表筛选数据帧,r,list,filter,R,List,Filter,我试图根据字符向量列表过滤数据帧,并获得每个向量的输出。下面是一个例子来澄清我的问题: 这就是我拥有的数据类型 fruit <- c("Apple", "Banana", "Cherry") vegetable <- c("Leek", "Courgette") ls <- list(fruit, vegetable) df <- data.frame(type = c(&
fruit <- c("Apple", "Banana", "Cherry")
vegetable <- c("Leek", "Courgette")
ls <- list(fruit, vegetable)
df <- data.frame(type = c("Apple", "Courgette", "Cherry"),
quantity = c(10, 5, 3))
从这个问题中得到启发:,我试着运行代码
newDF <- df[which((names(df) %in% fruit ==TRUE)),]
newDF试试这个:
#Code
L <- lapply(ls,function(x) data.frame(type=x[x %in% df$type]))
names(L) <- paste0('new_df_',c('fruit','vegetable'))
试试这个:
#Code
L <- lapply(ls,function(x) data.frame(type=x[x %in% df$type]))
names(L) <- paste0('new_df_',c('fruit','vegetable'))
我们可以使用ls
,子集
上的循环,使用list2env
创建新对象
list2env(setNames(lapply(ls, function(x) subset(df,
type %in% x, select = type)),
paste0('new_df_', c('fruit', 'vegetable'))), .GlobalEnv)
-输出
new_df_fruit
# type
#1 Apple
#3 Cherry
new_df_vegetable
# type
#2 Courgette
我们可以使用ls
,子集
上的循环,使用list2env
创建新对象
list2env(setNames(lapply(ls, function(x) subset(df,
type %in% x, select = type)),
paste0('new_df_', c('fruit', 'vegetable'))), .GlobalEnv)
-输出
new_df_fruit
# type
#1 Apple
#3 Cherry
new_df_vegetable
# type
#2 Courgette
如何得到水果载体的66%和50%,是66%,因为载体中存在的3个值中有2个也存在于df中。50%是因为2个值中有1个也在df中。如何得到66%和50%的水果载体是66%,因为载体中3个值中有2个也在df中。50%是因为2个值中有1个也在df中。