过滤循环以创建多个数据帧 [英] Filter loop to create multiple data frames

查看:43
本文介绍了过滤循环以创建多个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

I've got a dataframe structured like this:

df = data.frame(topic = c("xxx", "xxx", "yyy", "yyy", "yyy", "zzz", "zzz"), 
             high = c(52L, 27L, 89L, 99L, 43L, 21L, 90L), 
             low = c(56L, 98L, 101L, 21L, 98L, 40L, 43L), 
             stringsAsFactors = FALSE)

我想为主题列中的每个唯一值创建一个变量,同时保持所有观察结果不变.基本上就像循环此dplyr过滤器一样:

I would like to create a single variable for each unique value in the topic column, while keeping all the observations untouched. Basically it's like looping this dplyr filter:

zzz = df %>% filter (topic == "zzz")

应该很容易,所以我确定我在这里缺少一些基本知识...谢谢!

It should be easy, so I'm sure I'm missing some basic knowledge here... Thanks!

这是我关于stackoverflow的第一个问题,对于格式错误,我深表歉意.

It was my first question on stackoverflow, I apologize for the bad formatting.

推荐答案

df <- data.frame(topic = c("xxx", "xxx", "yyy", "yyy", "yyy", "zzz", "zzz"), 
                  high = c(52L, 27L, 89L, 99L, 43L, 21L, 90L), 
                  low = c(56L, 98L, 101L, 21L, 98L, 40L, 43L), 
                 stringsAsFactors = FALSE)

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

for (variable in unique(df$topic)) {
  assign(variable, df %>% filter (topic == variable), envir = .GlobalEnv)
}

xxx
#>   topic high low
#> 1   xxx   52  56
#> 2   xxx   27  98

yyy
#>   topic high low
#> 1   yyy   89 101
#> 2   yyy   99  21
#> 3   yyy   43  98

zzz
#>   topic high low
#> 1   zzz   21  40
#> 2   zzz   90  43

reprex软件包(v0.2.1)创建于2019-02-13

Created on 2019-02-13 by the reprex package (v0.2.1)

这篇关于过滤循环以创建多个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆