Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 按字符向量列表筛选数据帧_R_List_Filter - Fatal编程技术网

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中。