拆分后的数据框列名称 [英] Data frame column names after split

查看:58
本文介绍了拆分后的数据框列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下代码时

data <- data.frame( A = c("foo", "foo", "bar", "bar"),
                    B = c("foo","bar", "foo", "bar"),
                    C = c("bla", "foo", "bla", "bar"),
                    D = c(1, 2, 3, 4 ),
                    E = c(5, 6, 7, 8 ))

ds <- split(data, list(data$A, data$B, data$C), drop=TRUE)
write.table(ds[1], file="foo.csv", append=FALSE, row.names=FALSE)

foo.csv看起来像这样:

foo.csv looks like this:

 "bar.bar.bar.A","bar.bar.bar.B","bar.bar.bar.C","bar.bar.bar.D","bar.bar.bar.E"
 "bar","bar","bar",4,8

即列名称包含用于拆分的列的内容。如何以通用方式将名称改回原始名称? (我不想分配诸如 A, B等的列名。)

i.e., the column names contain the contents of the columns used to split. How do I change does names back to the original ones in a generic way? (I don't want to assign column names like "A", "B",....)

推荐答案

The split 的输出是列表 ds [1] 返回列表,而 ds [[1]] 返回该第一个列表项中的值。

The output of split is a list. ds[1] returns a list, while ds[[1]] returns the value within that first list item.

示例:

ds[1]
# $bar.bar.bar
#     A   B   C D E
# 4 bar bar bar 4 8

ds[[1]]
#     A   B   C D E
# 4 bar bar bar 4 8

获取输出正确地编写为CSV文件,则需要提取实际的 data.frame ,因此需要使用 ds [[1]] 方法。

To get the output properly written as a CSV file, you need to extract the actual data.frame, so you need to use the ds[[1]] approach.

write.table(ds[[1]], file="foo.csv", append=FALSE, row.names=FALSE)

如果要编写所有 data.frame 来分隔CSV文件,您可以执行以下操作:

If you wanted to write all of the data.frames to separate CSV files, you can do something like:

lapply(names(ds), function(x) {
  write.table(ds[[x]], file = paste(x, ".csv", collapse = ""),
              append = FALSE, row.names = FALSE)
})

这将创建四个CS工作目录中的V文件(名为bar.bar.bar.csv,bar.foo.bla.csv,foo.foo.bla.csv和foo.bar.foo.csv)。

This will create four CSV files (named bar.bar.bar.csv, bar.foo.bla.csv, foo.foo.bla.csv, and foo.bar.foo.csv) in your working directory.

这篇关于拆分后的数据框列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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