我按照Hadley的主题:Issue in Loading multiple .csv files into single dataframe in R using rbind来阅读多个private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
if ( this.dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "MachineName")
{
var model = this.dataGridView1.Rows[e.RowIndex].DataBoundItem as ServiceController;
if (model != null)
e.Value = model.MachineName;
}
}
文件,然后将它们转换为一个数据帧。我还在Grouping functions (tapply, by, aggregate) and the *apply family上讨论了CSV
与lapply
的实验。
这是我的第一个CSV文件:
sapply
这是我的第二个CSV文件:
dput(File1)
structure(list(First.Name = structure(c(1L, 2L, 1L, 1L, 1L), .Label = c("A",
"C"), class = "factor"), Last.Name = structure(c(1L, 2L, 2L,
2L, 2L), .Label = c("B", "D"), class = "factor"), Income = c(55L,
23L, 34L, 45L, 44L), Tax = c(23L, 21L, 22L, 24L, 25L), Location = structure(c(3L,
3L, 1L, 4L, 2L), .Label = c("Americas", "AP", "EMEA", "LATAM"
), class = "factor")), .Names = c("First.Name", "Last.Name",
"Income", "Tax", "Location"), class = "data.frame", row.names = c(NA,
-5L))
这是我的代码:
dput(File2)
structure(list(First.Name = structure(c(1L, 2L, 1L, 1L, 1L), .Label = c("A",
"C"), class = "factor"), Last.Name = structure(c(1L, 2L, 2L,
2L, 2L), .Label = c("B", "D"), class = "factor"), Income = c(55L,
55L, 55L, 55L, 55L), Tax = c(24L, 24L, 24L, 24L, 24L), Location = structure(c(3L,
3L, 1L, 4L, 2L), .Label = c("Americas", "AP", "EMEA", "LATAM"
), class = "factor")), .Names = c("First.Name", "Last.Name",
"Income", "Tax", "Location"), class = "data.frame", row.names = c(NA,
-5L))
虽然效果很好,但我想将dat1 <-",First.Name,Last.Name,Income,Tax,Location\n1,A,B,55,23,EMEA\n2,C,D,23,21,EMEA\n3,A,D,34,22,Americas\n4,A,D,45,24,LATAM\n5,A,D,44,25,AP"
dat2 <-",First.Name,Last.Name,Income,Tax,Location\n1,A,B,55,24,EMEA\n2,C,D,55,24,EMEA\n3,A,D,55,24,Americas\n4,A,D,55,24,LATAM\n5,A,D,55,24,AP"
tc1 <- textConnection(dat1)
tc2 <- textConnection(dat2)
merged_file <- do.call(rbind, lapply(list(tc1,tc2), read.csv))
更改为lapply
。从上面的线程中,我意识到sapply
会将读取因子从sapply
文件更改为矩阵,但我不确定为什么要翻转字段。例如,csv
字段占用第3行和第8行,但不在一列中。
以下是代码:
Income
这是输出:
tc1 <- textConnection(dat1)
tc2 <- textConnection(dat2)
# change lapply to sapply
merged_file <- do.call(rbind, sapply(list(tc1,tc2), read.csv))
我很感激任何帮助。我对R很新,不知道发生了什么。
答案 0 :(得分:1)
此问题与因素无关,它是通用的sapply
与lapply
。
为什么sapply
弄错了而lapply
弄错了? 请记住,在R中,数据框是列列表。,每一列可以具有不同的类型。
lapply
将列列表返回到rbind
,它可以正确地进行串联。它将相应的列保持在一起。这样您的因素就会正确显示。sapply
但是...
sapply
将您的两个5x6输入数据帧转换为转置6x5矩阵(列现在对应于行)... rbind
行-将这两个数字的6x5垃圾矩阵连接到一个非常垃圾的12x5矩阵中。由于列已转置为行,因此行级联矩阵将合并数据类型,显然您的因素被弄乱了。摘要:只需使用lapply