【问题标题】:`rbind` unique entries of all columns of a data frame and write it to a csv file`rbind` 数据框所有列的唯一条目并将其写入 csv 文件
【发布时间】:2016-12-29 06:10:29
【问题描述】:
##Initialise empty dataframe
g <-data.frame(x= character(), y= character(),z=numeric())

## Loop through each columns and list out unique values (with the column name)
for(i in 1:ncol(iris))
{
a<-data.frame(colnames(iris)[i],unique(iris[,i]),i)
g<-rbind(g,a)
setNames(g,c('x','y','z'))
}
## write the output to csv file
write.csv(g,"1.csv")

输出的 CSV 文件是这样的

现在我想要的列标题不正确。我希望列标题分别为“x”、“y”、“z”。第一列也不应该在那里。

另外,如果您有任何其他有效的方法来做到这一点,请告诉我。谢谢!

【问题讨论】:

标签: r dataframe


【解决方案1】:

这将完成工作:

for(i in 1:ncol(iris))
{
a<-data.frame(colnames(iris)[i],unique(iris[,i]),i)
g<-rbind(g,a)
}
g <- setNames(g,c('x','y','z'))   ## note the `g <-`
write.csv(g, file="1.csv", row.names = FALSE)   ## don't write row names

setNames 返回一个名为“x”、“y”和“z”的新数据框,而不是更新输入数据框g。您需要显式分配 &lt;- 来执行“替换”。您可以使用两者中的任何一个来隐藏此类&lt;-

names(g) <- c('x','y','z')
colnames(g) <- c('x','y','z')

或者,您可以在write.table 中使用col.names 参数:

for(i in 1:ncol(iris))
{
a<-data.frame(colnames(iris)[i],unique(iris[,i]),i)
g<-rbind(g,a)
}
write.table(g, file="a.csv", col.names=c("x","y","z"), sep =",", row.names=FALSE)

write.csv() 不支持col.names,因此我们使用write.table(..., sep = ",")。尝试在 write.csv 中使用 col.names 会产生警告。


更有效的方法

我会避免在循环中使用rbind。我会这样做:

x <- lapply(iris, function (column) as.character(unique(column)))
g <- cbind.data.frame(stack(x), rep.int(1:ncol(iris), lengths(x)))
write.table(g, file="1.csv", row.names=FALSE, col.names=c("x","y","z"), sep=",")

阅读?lapply?stack 了解更多信息。

【讨论】:

  • 我想在数据框 (g)/csv 文件中再增加一列(比如标签)。它将根据列的唯一条目数从 1 重复到 n。示例:对于 sepal.length,它将从 1 到 35...然后对于 sepal.width,它将再次从 1 到 22 开始。
猜你喜欢
  • 2019-10-05
  • 2021-10-18
  • 2021-05-27
  • 2020-06-15
  • 2019-02-05
  • 2020-06-01
  • 1970-01-01
  • 2016-05-30
  • 2017-03-29
相关资源
最近更新 更多