r语言 - 使用 by 函数保留'by'变量



使用by拆分数据帧时,将打印'by'变量,但不保留为变量。

    data(iris)
    dflist <- by(iris[,1:4], iris[,"Species"], data.frame)
    head(dflist[[1]])
      Sepal.Length Sepal.Width Petal.Length Petal.Width
    1          5.1         3.5          1.4         0.2
    2          4.9         3.0          1.4         0.2
    3          4.7         3.2          1.3         0.2
    4          4.6         3.1          1.5         0.2
    5          5.0         3.6          1.4         0.2

是否可以保留变量作为列变量如下所示?

        Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    1            5.1         3.5          1.4         0.2     setosa
    2            4.9         3.0          1.4         0.2     setosa
    3            4.7         3.2          1.3         0.2     setosa
    4            4.6         3.1          1.5         0.2     setosa
    5            5.0         3.6          1.4         0.2     setosa

或者是否有更好的方法将特定变量的数据分组到列表对象中?

如果您想保留物种列,那么您只需请求它。现在,您通过只选择列1:4来显式地删除它。

dflist <- by(iris[,1:5], iris[,"Species"], data.frame)
head(dflist[[1]])
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

或者此时,因为您只是拆分数据而没有应用函数

dflist <- split(iris, iris[,"Species"])

也可以

split可能会做你正在寻找的:

split(iris, iris$Species)
# $setosa
#    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1           5.1         3.5          1.4         0.2  setosa
# 2           4.9         3.0          1.4         0.2  setosa
# 3           4.7         3.2          1.3         0.2  setosa
# 4           4.6         3.1          1.5         0.2  setosa
# 5           5.0         3.6          1.4         0.2  setosa
# ...
# $versicolor
#     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# 51           7.0         3.2          4.7         1.4 versicolor
# 52           6.4         3.2          4.5         1.5 versicolor
# 53           6.9         3.1          4.9         1.5 versicolor
# 54           5.5         2.3          4.0         1.3 versicolor
# 55           6.5         2.8          4.6         1.5 versicolor
# ...

这是你想要的吗?

species_list <- split(iris,iris$Species,drop=FALSE)

相关内容

最新更新