我有一个这样的数据框:
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过滤器一样:
zzz = df %>% filter (topic == "zzz")
应该很容易,所以我确定这里缺少一些基本知识...谢谢!
编辑:这是我关于stackoverflow的第一个问题,对于格式错误,我深表歉意。
答案 0 :(得分:0)
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 package(v0.2.1)于2019-02-13创建
答案 1 :(得分:0)
您可以尝试以下操作:
topics <- unique(df$topic)
y <- lapply(1:length(topics), function(x) {dt %>% filter(topic==topics[x])})
names(y) <- topics
list2env(y , envir = .GlobalEnv)
最好!